【【7050】已知散列函数为H(key)=key mod 13,冲突处理方法为外拉链法实现散列表的建立(利用插入算法实现)】
文章图片
#include
using namespace std;
typedef struct node {node* next;
int data;
}LNode, * LinkList;
typedef struct hashlist { int ListLength;
LinkList list;
}HashList;
void List_Insert_HashList(HashList l, int key) {
//calculate p value
int p = 0;
for (int i = l.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 (l.list[h].data =https://www.it610.com/article/= 0) {
l.list[h].data = key;
}
else {
LinkList p = new LNode;
p->data = https://www.it610.com/article/l.list[h].data;
p->next = l.list[h].next;
l.list[h].data = https://www.it610.com/article/key;
l.list[h].next = p;
}}int main() {
int m = 13;
//create and initial hashlist
HashList l;
l.ListLength = m;
l.list = new LNode[m];
for (int i = 0;
i < m;
i++) {
l.list[i].data = 0;
l.list[i].next = NULL;
}
int key;
cin>> key;
while (key != 0) {
List_Insert_HashList(l, key);
cin >> key;
} for (int i = 0;
i < m;
i++) {
cout << i << ":";
if (l.list[i].data != 0) {
cout << l.list[i].data << " ";
}
LinkList p = l.list[i].next;
while (p != NULL) {
cout << p->data << " ";
p = p->next;
}
cout << "\n";
} return 0;
}
推荐阅读
- 【8555】编写在非递减有序链表中插入一个元素使链表元素仍有序的函数,并利用该函数建立一个非递减有序单向链表
- 【8560】采用单向链表实现一元多项式的存储并实现两个多项式相加并输出结果
- 【7051】已知散列函数为H(key)=key%p,冲突处理方法分别为线性探测法实现散列表的建立(插入算法实现)
- 【8553】随机产生或键盘输入一组元素,建立一个带头结点的单向链表(无序),遍历单向链表,显示相应元素