在数据结构和算法的学习中,C语言哈希表是一个非常重要的知识点。而链地址法(Chaining)是解决哈希冲突最常用、最直观的方法之一。本文将用通俗易懂的方式,手把手教你如何在C语言中实现链地址法哈希表,即使你是编程小白,也能轻松掌握!
哈希表通过哈希函数将键(key)映射到一个数组索引上。但不同的键可能被映射到同一个索引位置,这就叫哈希冲突。例如,假设我们的哈希函数是 key % 10,那么键 15 和 25 都会映射到索引 5。
链地址法的解决思路很简单:每个哈希表的“桶”(bucket)不再只存一个值,而是存储一个链表。当多个键映射到同一个索引时,就把它们串成一个链表。

我们将分以下几步实现链地址法哈希表:
typedef struct Node { int key; int value; struct Node* next;} Node;#define TABLE_SIZE 10typedef struct { Node* buckets[TABLE_SIZE];} HashTable;这里我们设定哈希表大小为10,每个桶是一个指向链表头节点的指针。
int hash(int key) { return key % TABLE_SIZE;}void initHashTable(HashTable* table) { for (int i = 0; i < TABLE_SIZE; i++) { table->buckets[i] = NULL; }}void insert(HashTable* table, int key, int value) { int index = hash(key); Node* newNode = (Node*)malloc(sizeof(Node)); newNode->key = key; newNode->value = value; newNode->next = table->buckets[index]; table->buckets[index] = newNode;}注意:这里采用“头插法”,新节点插入到链表头部,效率更高。
int search(HashTable* table, int key) { int index = hash(key); Node* current = table->buckets[index]; while (current != NULL) { if (current->key == key) { return current->value; } current = current->next; } return -1; // 表示未找到}void deleteKey(HashTable* table, int key) { int index = hash(key); Node* current = table->buckets[index]; Node* prev = NULL; while (current != NULL && current->key != key) { prev = current; current = current->next; } if (current == NULL) return; // 未找到 if (prev == NULL) { table->buckets[index] = current->next; } else { prev->next = current->next; } free(current);}#include <stdio.h>#include <stdlib.h>// 上面所有结构体和函数定义...int main() { HashTable table; initHashTable(&table); insert(&table, 15, 100); insert(&table, 25, 200); insert(&table, 5, 300); printf("Search 15: %d\n", search(&table, 15)); // 输出 100 printf("Search 25: %d\n", search(&table, 25)); // 输出 200 printf("Search 5: %d\n", search(&table, 5)); // 输出 300 deleteKey(&table, 25); printf("After delete 25, search 25: %d\n", search(&table, 25)); // 输出 -1 return 0;}通过本教程,你已经掌握了使用C语言冲突处理中的链地址法来构建哈希表。这种方法简单高效,非常适合初学者理解和实现。无论你是准备面试,还是学习数据结构,掌握哈希表编程教程中的这一核心技巧都至关重要。
记住:链地址法的核心在于“每个桶是一个链表”,冲突时只需把新元素加到链表中即可。希望这篇C语言哈希表教程对你有所帮助!
本文由主机测评网于2025-12-17发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://www.vpshk.cn/2025129250.html