哈希表
哈希表
例子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; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY