Hash表基本操作
2015-07-12 10:43
337 查看
#include<stdio.h> #include<stdlib.h> #define HASHSIZE 12 #define NULLKEY -32768 typedef struct _Hash { int *elmt; int count; }_Hash; typedef struct _Hash HashTable; int m = 0; void InitHash(HashTable* H) { int i; m = HASHSIZE; H->elmt = (int*)malloc(sizeof(int)*m); H->count = 0; for(i = 0;i < m; i++) { H->elmt[i] = NULLKEY; } } int Hash_(int key) { return key%m; } void InsertKey(HashTable* H,int key) { int pos = Hash_(key); int i = 0; while((H->elmt[pos])!= NULLKEY) { i++; pos = (pos+i)%HASHSIZE; if(pos == Hash_(key)) { printf("已经没有空位置给元素:%d\n",key); return ; } } (H->count)++; printf("第 %d 次插入:元素 %d 冲突 %d 次,插入位置:%d\n",H->count,key,i,pos); H->elmt[pos] = key; } int Search(HashTable H,int key) { int pos = Hash_(key); while(H.elmt[pos] != key)//冲突 { pos = (pos + 1)%HASHSIZE; if(H.elmt[pos] == NULLKEY || pos == Hash_(key)) { printf("没有找到元素%d\n",key); return -1; } } return pos; } int main() { int arr[HASHSIZE+1] = {2,3,7,4,6,8,1,5,9,18,10,-1,20}; int i,pos = 0; HashTable H; InitHash(&H); for(i = 0 ;i < HASHSIZE+1 ;i++) { InsertKey(&H,arr[i]); } for(i = 0 ;i < HASHSIZE+1 ;i++) { pos = Search(H,arr[i]); if(pos != -1) printf("元素:%d ,在位置:%d\n",arr[i],pos); } return 0; }
相关文章推荐
- 并查集小结
- jquery.callback.js jq 回调
- ViewData与ViewBag
- 笔试——2015BAT实习招聘
- 1.5光源;环境光与雾
- c++类之继承与派生
- 伪指令ADR和LDR的区别
- WLLN(Weak Law of Large Numbers) DEMO
- javascript定时器小结
- Iptables 入门进阶
- HDU5280 Senior's Array(简单DP)
- LeetCode #14 Longest Common Prefix
- 黑马程序员——JAVA基础---常量与变量
- 利用python3 requests和BeautifulSoup4抓取百度贴吧研究生录取通知书并展示
- [LeetCode][Java] Longest Valid Parentheses
- test
- 1.4 调试程序
- 【POJ】 【3624】
- MySQL 备份与还原详解
- 【Big Data】HADOOP集群的配置(二)