#include<iostream>
#include<string.h>
using namespace std;
void Insert_HashList(int* hashlist, int ListLength, int key) {
//calculate p value
int p = 0;
for (int i = ListLength; i > 0; i--) {
int flag = 0;
for (int j = i - 1; j > 1; j--) {
if (i % j == 0) {
flag = 1;
}
}
if (flag == 0) {
p = i;
break;
}
}
int h = key % p;
if (hashlist[h] == 0) {
hashlist[h] = key;
}
else {
int count = 0;
while (hashlist[h] != 0) {
h = (h + 1) % ListLength;
count++;
if (count > ListLength) {
cout << "list overflow!!!!" << endl;
break;
}
}
hashlist[h] = key;
}
}
int main() {
int m;
cin >> m;
int* hashlist = new int[m];
memset(hashlist, 0, sizeof(hashlist) * (m-1));
int a;
cin >> a;
while (a!=0) {
Insert_HashList(hashlist, m, a);
cin >> a;
}
for (int i = 0; i < m; i++) {
cout << i << " ";
}
cout << "\n";
for (int i = 0; i < m; i++) {
cout << hashlist[i] << " ";
}
return 0;
}```
【7051】已知散列函数为H(key)=key%p,冲突处理方法分别为线性探测法实现散列表的建立(插入算法实现)
最新推荐文章于 2022-12-01 11:41:28 发布