第11章 散列表
2015-08-03 10:40
225 查看
#include<stdio.h> #include<stdlib.h> unsigned int hashIndex1(const char *key, unsigned int tablesize) { unsigned int val = 0; while (*key != '\0') val += *key++; return val%tablesize; } unsigned int hashIndex2(const char *key, unsigned int tablesize) { return (key[0] + 27 * key[1] + 729 * key[2]) % tablesize; } unsigned int hashIndex3(const char *key, unsigned int tablesize) { unsigned int val = 0; while (*key != '\0') val = (val << 5) + *key++; return val%tablesize; } unsigned int hashIndex4(unsigned int key, unsigned int tablesize) { return key%tablesize; } struct ListNode{ int value; ListNode* next; }; struct HashTab{ int tablesize; ListNode** list; }; HashTab initializeTable(int tablesize) { HashTab h; h.tablesize = tablesize; h.list = (ListNode**)malloc(sizeof(ListNode*)*tablesize); for (int i = 0; i < tablesize; ++i) h.list[i] = NULL; return h; } ListNode* FindHash(HashTab h, int key) { ListNode* L = h.list[ hashIndex4(key, h.tablesize) ]; while (L&&L->value != key) L = L->next; return L; } void InsertHash(HashTab h, int key) { ListNode* p = FindHash(h, key); if (p == NULL){ ListNode* newcell = (ListNode*)malloc(sizeof(ListNode)); newcell->next = NULL; newcell->value = key; //printf("%d\n", hashIndex4(key, h.tablesize)); int index = hashIndex4(key, h.tablesize); if (h.list[index] == NULL) h.list[index] = newcell; else{ newcell->next = h.list[index]; h.list[index] = newcell; } } } void printHash(HashTab h) { ListNode* tmp; for (int i = 0; i < h.tablesize; ++i){ tmp = h.list[i]; while (tmp){ printf("%d\t", tmp->value); tmp = tmp->next; } printf("\n"); } } int main() { int a[] = { 4, 2, 2, 0, 20, 11, 15, 18, 20, 13 }; HashTab h = initializeTable(5); for (int i = 0; i < 10; ++i) InsertHash(h, a[i]); printHash(h); }
相关文章推荐
- 覆盖度统计及测试流程
- COPY 构建亿级前端读服务
- 南邮 OJ 1024 01排序
- 7. Document write() 方法
- 欢迎使用CSDN-markdown编辑器
- awk 两个文件的两个列若相同,合并两个文件
- poj1797
- windows 判断环境变量有无输入正确 echo %JAVA_HOME%
- [深入理解Android卷二 全文-第二章]深入理解Java Binder和MessageQueue
- 7月国内网站流量统计TOP5:百度腾讯涨幅明显
- 怎么用pfSense为你的web服务做负载均衡
- 在命令行界面使用vs2008的cl 进行编译
- iOS 去掉系统bar自带的线
- javascript实现超炫的向上滑行菜单实例
- 作业盒子刘夜: 我如何获得奶茶妹妹“处女投”
- Highcharts中字符串处理方式(1)
- css大会网站顶部的一个特效
- shell 总结 单引号 双引号 花括号
- POJ 1035 Spell checker(暴力)
- 2015.08.03,学习,学习笔记-《通过翻译学英语》学习笔记(2)