描述
请写出在散列表中删除关键字为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
思路:
注意:oj里使用的是尾插法!!!
这个题目中要求的哈希表和邻接表的处理方法非常类似,所以如果你还没有掌握邻接表的话,推荐先去做邻接表部分的题。同时,在我的这篇文章中,借助4003这道题比较详细地讲解了邻接表的插入,初始化等操作:
(15条消息) 4003基于邻接表的新顶点的增加(C++,附详细解析)_鹤天寻的博客-CSDN博客https://blog.csdn.net/qq_54416938/article/details/121582300?spm=1001.2014.3001.5501在4020中,也用到了邻接表,插入操作可以看这篇文章:
所以在以下思路中,默认你已经会了邻接表的相关操作了~
这个题目的操作是删除,那么删除的话需要遍历整个链表,到时候输出又遍历一遍,重复了,不妥;那怎么办呢?只要不输出那个数不就可以了吗?所以只需要写两个函数,一个创建,一个输出,把“删除”当作是控制输出格式那样去想即可,遇到了要“删除”的数字,跳过即可。
代码如下:
#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<stack>
#include<set>
#include<map>
using namespace std;
typedef struct LNode
{
int data;
struct LNode* next;
}*linklist, LNode;
void Create(linklist& vl, int n)
{
vl = new LNode[13];
for (int i = 0; i < 13; i++)
{
vl[i].data = i;
vl[i].next = NULL;
}
//尾插法
for (int i = 0; i < n; i++)
{
int temp;
cin >> temp;
linklist p = new LNode, r = &vl[temp % 13];
while (r->next)
r = r->next;
p->data = temp;
p->next = NULL;
r->next = p;
}
}
void Show(linklist vl)
{
int x;
cin >> x;
for (int i = 0; i < 13; i++)
{
cout << i;
linklist p = vl[i].next;
while (p)
{
if (p->data == x)
cout << "";
else
cout <<' '<< p->data;
p = p->next;
}
cout << endl;
}
}
int main()
{
int n;
while (cin >> n && n != 0)
{
linklist vl;
Create(vl, n);
Show(vl);
}
return 0;
}