C语言哈希表的基础操作实现

以上就是我本人在学习了简单的哈希表之后,自己写出来的简单代码,有不好的地方可以指出来,多多指教!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是C语言哈希表的基本操作代码: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #define TABLE_SIZE 100 typedef struct Node { char* key; char* value; struct Node* next; } Node; Node* table[TABLE_SIZE]; unsigned int hash(char* key) { unsigned int hash = 0; for (int i = 0; i < strlen(key); i++) { hash = hash * 31 + key[i]; } return hash % TABLE_SIZE; } void put(char* key, char* value) { unsigned int index = hash(key); Node* node = table[index]; while (node != NULL) { if (strcmp(node->key, key) == 0) { node->value = value; return; } node = node->next; } node = (Node*)malloc(sizeof(Node)); node->key = key; node->value = value; node->next = table[index]; table[index] = node; } char* get(char* key) { unsigned int index = hash(key); Node* node = table[index]; while (node != NULL) { if (strcmp(node->key, key) == 0) { return node->value; } node = node->next; } return NULL; } void remove_key(char* key) { unsigned int index = hash(key); Node* node = table[index]; Node* prev = NULL; while (node != NULL) { if (strcmp(node->key, key) == 0) { if (prev == NULL) { table[index] = node->next; } else { prev->next = node->next; } free(node); return; } prev = node; node = node->next; } } void print_table() { for (int i = 0; i < TABLE_SIZE; i++) { printf("%d: ", i); Node* node = table[i]; while (node != NULL) { printf("(%s, %s) ", node->key, node->value); node = node->next; } printf("\n"); } } int main() { put("apple", "red"); put("banana", "yellow"); put("orange", "orange"); print_table(); printf("apple: %s\n", get("apple")); printf("banana: %s\n", get("banana")); printf("orange: %s\n", get("orange")); remove_key("banana"); print_table(); return 0; } ``` 这段代码实现哈希表的基本操作,包括插入、查找、删除和打印哈希表。其中,哈希函数使用了简单的字符串哈希算法,冲突解决采用了链表法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值