基于链地址法的散列表的删除
描述
请写出在散列表中删除关键字为k的一个记录的算法,设散列函数为H,H(key)=key%13,解决冲突的方法为链地址法。
输入
多组数据,每组三行,第一行为待输入的关键字的个数n,第二行为对应的n个关键字,第三行为需要删除的关键字k。当n=0时输入结束。
输出
每组数据输出用链地址法处理冲突的散列表。
输入样例 1
5 1 4 2 3 5 3 4 1 10 14 27 14 0
输出样例 1
0 1 1 2 2 3 4 4 5 5 6 7 8 9 10 11 12 0 1 1 27 2 3 4 5 6 7 8 9 10 10 11 12
#include<iostream>
using namespace std;
typedef struct LNode {
int data;
struct LNode* next;
}LNode,*LinkList;
LinkList h[13];
void Hash(int n) {
for (int i = 0; i < 13; i++) {
h[i] = new LNode;
h[i]->next = NULL;
}
int x;
for (int i = 0; i < n; i++) {
cin >> x;
LNode* p = h[x % 13];
while (p->next) {
p = p->next;
}
LNode* s = new LNode;
s->data = x;
s->next = p->next;
p->next = s;
}
}
void Delete(int x) {
LNode* p = h[x % 13];
while (p) {
if (p->next->data == x) {
p->next = p->next->next;
break;
}
p = p->next;
}
}
void Output() {
for (int i = 0; i < 13; i++) {
cout << i;
LNode* p = h[i]->next;
while (p) {
cout << " " << p->data;
p = p->next;
}
cout << endl;
}
}
int main() {
int n;
while (cin >> n && n != 0) {
Hash(n);
int x;
cin >> x;
Delete(x);
Output();
}
}