使用链表解决哈希冲突问题,即多个元素通过链表存储在同一个哈希桶中。
#include <stdio.h>
#include <stdlib.h>
#define SIZE 9 // 定义哈希表的大小
// 定义链表节点结构体,表示哈希表中的元素
typedef struct LNode {
int key; // 存储键值
struct LNode *next; // 指向下一个节点的指针
} *Node;
// 定义哈希表结构体
typedef struct HashTable {
struct LNode *table; // 哈希表由一个链表数组构成
} *HashTable;
// 初始化哈希表
void initHashTable(HashTable ht) {
// 为哈希表的每个桶分配内存
ht->table = malloc(sizeof(struct LNode) * SIZE);
for (int i = 0; i < SIZE; i++) {
// 初始化每个桶的key为-1,next为NULL
ht->table[i].key = -1;
ht->table[i].next = NULL;
}
}
// 哈希函数,将key映射到一个索引
int hash(int key) {
return key % SIZE; // 取余操作,得到的结果即为哈希索引
}
// 创建一个新的链表节点
Node createNode(int key) {
Node node = malloc(sizeof(struct LNode)); // 为新节点分配内存
node->key = key; // 设置节点的键值
node->next = NULL; // 新节点的next指针为NULL
return node;
}
// 向哈希表中插入一个元素
void insert(HashTable ht, int key) {
int index = hash(key); // 计算该元素的哈希值(索引)
Node head = ht->table + index; // 定位到哈希表中对应桶的位置
while (head->next) // 如果当前桶已经有元素,找到链表的末尾
head = head->next;
head->next = createNode(key); // 在链表末尾插入新节点
}
// 查找元素是否在哈希表中
_Bool find(HashTable ht, int key) {
int index = hash(key); // 计算该元素的哈希值(索引)
Node head = ht->table + index; // 定位到哈希表中对应桶的位置
while (head->next && head->key != key) // 遍历链表,直到找到元素或链表末尾
head = head->next;
return head->key == key; // 如果找到元素,返回1,否则返回0
}
// 主函数
int main(void) {
struct HashTable ht; // 定义一个哈希表
initHashTable(&ht); // 初始化哈希表
insert(&ht, 10); // 插入元素10
insert(&ht, 19); // 插入元素19
insert(&ht, 20); // 插入元素20
printf("%d\n", find(&ht, 20)); // 查找元素20,输出1(找到)
printf("%d\n", find(&ht, 17)); // 查找元素17,输出0(未找到)
printf("%d\n", find(&ht, 19)); // 查找元素19,输出1(找到)
}