哈希表C语言实现

哈希表

#include <stdio.h>
#include "stdlib.h"
#define HASHSIZE 12    /*定义哈希表长为数组的长度*/
#define NULLKEY -32768

// 定义哈希表 (使用的是动态数组来进行保存)
typedef struct HashTable {
    int len;
    int *elem;
}HashTable;

// 初始化哈希表
int initHashTable(HashTable *hashTable) {
    hashTable->len = HASHSIZE;
    hashTable->elem = (int *)malloc(HASHSIZE *sizeof(int));
    for (int i = 0; i < HASHSIZE; ++i) {
        hashTable->elem[i] = NULLKEY;
    }
    return 1;
}


// 定义哈希函数
int Hash(int key) {
    return key % HASHSIZE;
}

// 插入操作
void insertHashTable(HashTable *hashTable, int key) {
    int addr = Hash(key);
    while (hashTable->elem[addr] != NULLKEY){        // 出现冲突
        // 使用开放定址法,查看下一个是否冲突
        addr = (addr + 1) % HASHSIZE;
    }
    hashTable->elem[addr] = key;
}

// 查询操作
int queryHashTable(HashTable *hashTable, int key) {
    int addr = Hash(key);
    while (hashTable
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的哈希表C语言实现代码,使用链地址法解决哈希冲突: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #define HASHSIZE 12 #define NULLKEY -32768 typedef struct { int *elem; // 数据元素存储基址,动态分配数组 int count; // 当前数据元素个数 } HashTable; int InitHashTable(HashTable *H) { int i; H->count = HASHSIZE; H->elem = (int *)malloc(HASHSIZE * sizeof(int)); for (i = 0; i < HASHSIZE; i++) { H->elem[i] = NULLKEY; } return 1; } int Hash(int key) { return key % HASHSIZE; // 散列函数采用除留余数法 } void InsertHash(HashTable *H, int key) { int addr = Hash(key); // 求哈希地址 while (H->elem[addr] != NULLKEY) { // 如果不为空,则冲突 addr = (addr + 1) % HASHSIZE; // 开放定址法的线性探测 } H->elem[addr] = key; // 直到有空位后插入关键字 } int SearchHash(HashTable H, int key) { int addr = Hash(key); // 求哈希地址 while (H.elem[addr] != key) { // 如果不相等,则冲突 addr = (addr + 1) % HASHSIZE; // 开放定址法的线性探测 if (H.elem[addr] == NULLKEY || addr == Hash(key)) { // 如果循环回到原点或者遇到空位,则说明关键字不存在 return -1; } } return addr; // 找到关键字,返回其地址 } int main() { HashTable H; int i, key, result; InitHashTable(&H); printf("请输入%d个数:\n", HASHSIZE); for (i = 0; i < HASHSIZE; i++) { scanf("%d", &key); InsertHash(&H, key); } printf("哈希表的数据为:\n"); for (i = 0; i < HASHSIZE; i++) { printf("%d ", H.elem[i]); } printf("\n请输入要查找的数:\n"); scanf("%d", &key); result = SearchHash(H, key); if (result == -1) { printf("没有找到%d\n", key); } else { printf("%d的位置是%d\n", key, result); } return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值