本文共 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/