C语言实现hashmap的方式有很多,最简单的就是使用数组实现,个人原创,源码如下:
#include <stdio.h> #include<string.h> #include<stdlib.h> typedef struct hashnode { char key[10]; //键 int value; //值 }; typedef struct { int size; int length; struct hashnode*Array; }Hashmap; Hashmap*hashmap; unsigned int hash_33(char* key)//哈希算法 { unsigned int hash = 0; while (*key) { hash = (hash << 5) + hash + *key++; } return hash; } void init()//初始化哈希表 { int i=0; hashmap=(Hashmap*)calloc(10,sizeof(Hashmap)); for(i=0;i<10;i++) { hashmap[i].Array=(struct hashnode*)calloc(10,sizeof(struct hashnode)); hashmap[i].size=10; hashmap[i].length=0; } } void add(char* key,int value)//添加key-value { int hashcode=hash_33(key)%10; Hashmap* hm=hashmap+hashcode; int index=hm->length; int i; if (index>=hm->size)//数组扩容 { int size=hm->size*2; hm->Array=(struct hashnode*)realloc(hm->Array,size*sizeof(struct hashnode)); hm->size=size; } for(i=0;i<hm->size;i++) { if (strcmp(hm->Array[i].key,key)==0)//key相同就覆盖 { hm->Array[i].value=value; break; } else { strcpy(hm->Array[i].key,key); hm->Array[i].value=value; hm->length++; break; } } } void print()//遍历哈希表 { int i,j; if (hashmap==NULL) { puts("hashmap为空"); return; } for (i=0;i<10;i++) { Hashmap sm=hashmap[i]; putchar('|'); for (j = 0; j < sm.length; j++) { printf("%s=%d",sm.Array[j].key,sm.Array[j].value); } printf("|\n"); } } void empty() //清空哈希表 { int i,j; for (i=0;i<10;i++) { Hashmap* sm=hashmap+i; free(sm->Array); sm->Array=NULL; } free(hashmap); hashmap=NULL; } int main(void) { init(); add("a",1); add("b",1); add("a",2); add("c",1); add("d",10); add("a",1); add("b",1); add("a",2); add("c",1); add("d",10); print(); empty(); print(); getchar(); return 0; }
目前只支持增加、遍历、清空功能。
有兴趣的读者可以自行实现删除、查找、替换.......等功能。
运行结果如图:
欢迎交流
个人QQ:757368775
【注意】
添加好友时请注明“来自c语言网”
0.0分
0 人评分
2004年秋浙江省计算机等级考试二级C 编程题(2) (C语言代码)浏览:670 |
C语言训练-舍罕王的失算 (C语言代码)浏览:1033 |
C语言程序设计教程(第三版)课后习题8.4 (Java代码)浏览:732 |
C二级辅导-统计字符 (C语言代码)浏览:506 |
C语言训练-角谷猜想 (C语言代码)浏览:1705 |
【计算两点间的距离】 (C语言代码)浏览:883 |
C语言考试练习题_排列 (C语言代码)浏览:725 |
母牛的故事 (C语言代码)浏览:932 |
C语言程序设计教程(第三版)课后习题5.7 (Java代码)浏览:889 |
1124题解浏览:595 |