博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Hash表的建立,插入与查找实现(C++)
阅读量:4049 次
发布时间:2019-05-25

本文共 1735 字,大约阅读时间需要 5 分钟。

本文实现了一个基本的HASH表的构建插入和查找过程。主要函数功能如下:

bool InitHashTable(HashTable &H);   //hash表的初始化int Hash(const int key);   //哈希函数,计算地址bool InsertHash(HashTable &H, const int key);   //插入新元素bool SearchHash(HashTable &H, const int key, int &add);   //删除新元素

函数结果示例:

Please input Hash Table size: 8#1 (q to quite): 56#2 (q to quite): 89#3 (q to quite): 23#4 (q to quite): 46#5 (q to quite): 81#6 (q to quite): 2#7 (q to quite): 6#8 (q to quite): 8Enter number you want to find: 81Find 81 at 2.

完整代码:

#include
#define UNLLKEY -32768using namespace std;struct HashTable{
int *elem; int count;};int HASHSIZE;bool InitHashTable(HashTable &H){
cout << "Please input Hash Table size: "; cin >> H.count; HASHSIZE = H.count; H.elem = new int[H.count]; for (int i = 0; i < H.count; i++) H.elem[i] = UNLLKEY; return true;}int Hash(const int key){
return key%HASHSIZE;}bool InsertHash(HashTable &H, const int key){
int add = Hash(key); while (H.elem[add] != UNLLKEY) add = (add + 1) % HASHSIZE; H.elem[add] = key; return true;}bool SearchHash(HashTable &H, const int key, int &add){
add = Hash(key); while (H.elem[add] != key) {
add = (add + 1) % HASHSIZE; if (H.elem[add] == UNLLKEY || add == Hash(key)) return false; } return true;}void main(){
HashTable H; InitHashTable(H); int temp, i = 0; cout << "#" << i + 1 << " (q to quite): "; while(i
> temp) {
InsertHash(H, temp); i++; if (i == HASHSIZE) break; cout << "#" << i + 1 << " (q to quite): "; } cin.clear(); while (cin.get() != '\n') continue; cout << "Enter number you want to find: "; cin >> temp; int add; if (SearchHash(H, temp, add)) cout << "Find " << H.elem[add] << " at " << add << ".\n"; else cout << "There is no " << temp << endl;}

转载地址:http://cpyci.baihongyu.com/

你可能感兴趣的文章
No.147 - LeetCode1108
查看>>
No.174 - LeetCode1305 - 合并两个搜索树
查看>>
No.175 - LeetCode1306
查看>>
No.176 - LeetCode1309
查看>>
No.182 - LeetCode1325 - C指针的魅力
查看>>
mysql:sql alter database修改数据库字符集
查看>>
mysql:sql truncate (清除表数据)
查看>>
yuv to rgb 转换失败呀。天呀。谁来帮帮我呀。
查看>>
yuv420 format
查看>>
yuv420 还原为RGB图像
查看>>
LED恒流驱动芯片
查看>>
驱动TFT要SDRAM做为显示缓存
查看>>
使用file查看可执行文件的平台性,x86 or arm ?
查看>>
qt5 everywhere 编译summary
查看>>
qt 创建异形窗体
查看>>
可重入函数与不可重入函数
查看>>
简单Linux C线程池
查看>>
内存池
查看>>
输入设备节点自动生成
查看>>
GNU hello代码分析
查看>>