//运用除余法构造散列函数,并用拉链法解决地址冲突的散列表构造及其检索算法。
#include <iostream>
#include <cstdio>
#define N 100
using namespace std;
typedef int ElemType;
typedef struct LNode{
ElemType data;
struct LNode* next;
}* LinkList, LNode;
int primeNum(int num) {// 求最大质数
int answer;
while (num > 0)
{
int flag = 1;
for (int i = 2; i * i <= num; i++)
{
if (num % i == 0)
{
flag = 0;
break;
}
}
if (flag == 1 || num == 2)
{
answer = num;
break;
}
num--;
}
return answer;
}
int getHash(int key, int num) {// 求hash值
return key % primeNum(num);
}
LinkList* createList(ElemType datas[], int num) {
LinkList HT[N];// 存放各链表头指针
for (int i = 0; i < primeNum(num); i++) {
int addr = getHash(datas[i], num);
HT[addr]->data = datas[i];
HT[addr] = HT[addr]->next;
}
return HT;
}
void search(ElemType data, int num, LinkList* HT) {
int addr = getHash(data, num);
while (true) {
if (HT[addr]->next == NULL) {
cout << "改数据不存在!" << endl;
break;
}
if (HT[addr]->data == data) {
cout << "该数据存在!" << endl;
break;
}
HT[addr] = HT[addr]->next;
}
}
int main(void) {
cout << "请输入数据个数:" << endl;
int num;
cin >> num;
int addr[N];
ElemType datas[N];
cout << "请输入数据:" << endl;
for (int i = 0; i < num; i++) {
cin >> datas[i];
}
LinkList* HT = createList(datas, num);
cout << "请输入要查找的数据" << endl;
int numa;
cin >> numa;
search(numa, num, HT);
}
如图
这为什么会访问冲突?