#include
using namespace std;
#define MAXSIZE 17
enum { No, Yes};
typedef struct node
{ //关键字结点
int data; //关键字
struct node *pNext; //指向下一个结点
}Node;
typedef struct Table
{
Node *table; //动态分配哈希表
int count; //哈希表的关键字个数
}HashTable;
void InitHashTable(HashTable &H) //初始化哈希表
{
H.count = MAXSIZE; //初始化哈希表的大小
H.table = new Node[H.count]; //创建哈希表
for (int i = 0; i < H.count; ++i) //初始化哈希表的数据
{
H.table[i].data = No;
H.table[i].pNext = NULL;
}
}
int Hash(int key)
{
return key%MAXSIZE;
}
void InsertHashTable(HashTable &H, int key) //将关键字key插入哈希表
{
int addr = Hash(key);
if (H.table[addr].data == No)
H.table[addr].data = Yes;
Node *pNew = new Node;
pNew->data = key;
pNew->pNext = H.table[addr].pNext;
H.table[addr].pNext = pNew;
pNew = NULL;
}
bool SearchHashTable(HashTable &H, int key) //查找关键字key的值
{
int addr = Hash(key);
if (H.table[addr].data == Yes)
{
Node *p = H.table[addr].pNext;
while (p) //查找单链表
{
if (p->data == key)
return true;
else
p = p->pNext;
}
}
return false;
}
void PrintHashTable(HashTable H)
{
int i;
Node* p = NULL;
for (i = 0; i < MAXSIZE; ++i)
{
if (H.table[i].data==Yes)
{
cout << i << ":";
p = H.table[i].pNext;
while (p)
{
cout << p->data << "→";
p = p->pNext;
}
cout <
}
}
}
void main()
{
HashTable H;
InitHashTable(H);
for (int i = MAXSIZE * 6-1; i>0; --i)
InsertHashTable(H, i);
PrintHashTable(H);
printf("请输入要查找的内容:\n");
int key;
cin >> key;
if (SearchHashTable(H, key))
printf("在哈希表中找到关键字:%d\n", key);
else
printf("在哈希表中未找到关键字:%d\n", key);
}