哈希表
哈希表
例子1:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TABLE_SIZE 100
// 哈希表中存储的键值对结构体
typedef struct KeyValuePair {
char* key;
int value;
struct KeyValuePair* next; // 指向下一个键值对的指针
} KeyValuePair;
// 哈希表结构体
typedef struct {
KeyValuePair* table[TABLE_SIZE];
} HashTable;
// 计算哈希值
int hash(char* key) {
int hash = 0;
for (int i = 0; key[i] != '\0'; i++) {
hash = (hash + key[i]) % TABLE_SIZE;
}
return hash;
}
// 创建哈希表
HashTable* createHashTable() {
HashTable* ht = (HashTable*)malloc(sizeof(HashTable));
for (int i = 0; i < TABLE_SIZE; i++) {
ht->table[i] = NULL; // 初始化每个槽位为空链表
}
return ht;
}
// 插入键值对到哈希表
void insert(HashTable* ht, char* key, int value) {
int index = hash(key);
KeyValuePair* kvp = (KeyValuePair*)malloc(sizeof(KeyValuePair));
kvp->key = strdup(key);
kvp->value = value;
kvp->next = NULL;
// 检查该位置是否已经存在节点
KeyValuePair* curr = ht->table[index];
KeyValuePair* prev = NULL;
while (curr != NULL) {
if (strcmp(curr->key, key) == 0) {
// 键已经存在,更新值并返回
curr->value = value;
free(kvp->key); // 释放键的内存,因为键已经存在
free(kvp); // 释放键值对的内存
return;
}
prev = curr;
curr = curr->next;
}
// 如果该位置为空,则直接将键值对插入
if (prev == NULL) {
ht->table[index] = kvp;
} else { // 否则,将键值对添加到链表末尾
prev->next = kvp;
}
}
// 查找键对应的值
int find(HashTable* ht, char* key) {
int index = hash(key);
KeyValuePair* curr = ht->table[index];
while (curr != NULL) {
if (strcmp(curr->key, key) == 0) {
return curr->value;
}
curr = curr->next;
}
return -1; // 没有找到
}
// 销毁哈希表
void destroyHashTable(HashTable* ht) {
for (int i = 0; i < TABLE_SIZE; i++) {
KeyValuePair* curr = ht->table[i];
while (curr != NULL) {
KeyValuePair* temp = curr;
curr = curr->next;
free(temp->key);
free(temp);
}
}
free(ht);
}
int main() {
HashTable* ht = createHashTable();
insert(ht, "apple", 5);
insert(ht, "banana", 10);
insert(ht, "orange", 15);
insert(ht, "grape", 20);
insert(ht, "apple", 25); // 重复键,将会形成链表
printf("apple: %d\n", find(ht, "apple"));
printf("banana: %d\n", find(ht, "banana"));
printf("orange: %d\n", find(ht, "orange"));
printf("grape: %d\n", find(ht, "grape"));
destroyHashTable(ht);
return 0;
}