本文实现了一个基本的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): 8
Enter number you want to find: 81
Find 81 at 2.
完整代码:
#include<iostream>
#define UNLLKEY -32768
using 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<HASHSIZE&&cin >> 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;
}