C语言实现hashmap的方式有很多,最简单的就是使用数组实现,个人原创,源码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 | #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 人评分
C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:
一点编程也不会写的:零基础C语言学练课程
解决困扰你多年的C语言疑难杂症特性的C语言进阶课程
从零到写出一个爬虫的Python编程课程
只会语法写不出代码?手把手带你写100个编程真题的编程百练课程
信息学奥赛或C++选手的 必学C++课程
蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程
发表评论 取消回复