我使用的是线性探测法处理冲突解决冲突
#include<iostream>
using namespace std;
typedef int KeyType;
typedef int InfoType;
#define SIZE 13
#define P 13
typedef struct {
KeyType key; /*KeyType由用户定义*/
InfoType otherinfo; /*此类型依赖于应用*/
}NodeType;
typedef NodeType Seqlist[SIZE];
NodeType hasht[SIZE];
void insertHTable(KeyType data)
{
/*插入hash表*/
int hash_value = data % P;
int i;
// 线性探测法处理冲突 hash_value + i) % P
for (i = 0; hasht[(hash_value + i) % P].key != 0; ++i);
hasht[(hash_value + i) % P].key = data;
}
void hashTable(Seqlist R)
{
/*构建hash表*/ // 结构: 邻接表
int hash_value;
for (int i = 0; i < SIZE; ++i)
{
cin >> R[i].key;
insertHTable(R[i].key);
}
}
int hashSearch(Seqlist R, KeyType K)
{
//计算hash_value
int hash_value = K % P;
//查找hash表
int i;
for (i = 0; i < SIZE; ++i)
{
if (hasht[(hash_value + i) % P].key == K)
return (hash_value + i) % P;
}
return -1;
}
int main()
{
Seqlist R;
KeyType K;
//初始化hash表
for (int i = 0; i < SIZE; ++i)
{
hasht[i].key = 0;
}
cout << "请输入13个无序整数: " << endl;
hashTable(R);
// 打印hash表
cout << "hash表: " << endl;
for (int i = 0; i < SIZE; ++i)
{
cout << hasht[i].key << " ";
}
cout << endl;
while (1)
{
cout << "请输入要查找的整数: ";
cin >> K;
cout << "hash查找: " << endl;
int index = hashSearch(R, K);
if (index == -1)
{
cout << "找不到" << K << endl;
}
else
{
cout << K << "在下标 " << index << endl;
}
cout << endl;
}
return 0;
}