分数 30
设哈希表长为10,哈希函数为: H(k)=k MOD 10 建立对应的哈希表。采用链地址法解决冲突。先建立哈希表,再删除x,插入y后,输出哈希表。
输入格式:
输入数据为初始元素个数和序列,以及x、y的值
输出格式:
输出数据为最后的哈希表
输入样例:
12
16 74 60 43 54 90 46 31 29 88 77 26
77 38
输出样例:
0->90->60^
1->31^
2^
3->43^
4->54->74^
5^
6->26->46->16^
7^
8->38->88^
9->29^
#include <stdio.h>
#include <stdlib.h>
struct HTNode//储存值和下一个结点的结构体
{
int key;
struct HTNode *next;
};
struct HashTable//储存头结点的结构体
{
struct HTNode *head;
};
void InstHT(HashTable ha[],int n)
{
for(int i=0;i<n;i++)
{
ha[i].head=NULL;
}
}
void CreateHT(HashTable ha[],int n,int data)//创建哈希表
{
int t=data%10;//计算哈希地址序号
if(ha[t].head==NULL)//如果该序号的头结点为空
{
HTNode *p;
p=(struct HTNode*)malloc(sizeof(struct HTNode));
p->key=data;//储存数据
p->next=NULL;//将下一个结点设置为空
ha[t].head=p;//赋值给头结点
}
else//如果头结点不为空,头插法
{
HTNode *p,*q;
p=ha[t].head;
q=(struct HTNode*)malloc(sizeof(struct HTNode));
q->key=data;
q->next=p;
ha[t].head=q;//将新的结点接到头结点后
}
}
void print(HashTable ha[]){
HTNode *p,*q;
for(int i=0;i<10;i++){
p=ha[i].head;
printf("%d",i);
if(p==NULL){
printf("^\n");
}else{
printf("->");
while(p!=NULL){
printf("%d",p->key);
if(p->next!=NULL)printf("->");
else
printf("^");
p=p->next;
}
printf("\n");
}
}
}
void Insert(int data,HashTable ha[]){
int t=data%10;
HTNode *p=ha[t].head,*q;
q=(struct HTNode*)malloc(sizeof(struct HTNode));
q->key=data;
q->next=p;
ha[t].head=q;//将新的结点接到头结点后
}
int DelHash(HashTable ha[],int data){
int t=data%10;
HTNode *p=ha[t].head,*q;
if(p==NULL)
return 0;
if(p->key==data){
ha[t].head=p->next;
}else{
while(p->next->key!=data && p->next!=NULL){
p=p->next;
}
q=p;
p=p->next;
q->next=p->next;
}
return 1;
}
int main()
{
int n,data;
scanf("%d",&n);
HashTable ha[100];
InstHT(ha,10);
for(int i=0;i<n;i++)
{
scanf("%d",&data);
CreateHT(ha,n,data);
}
scanf("%d",&data);
DelHash(ha,data);
scanf("%d",&data);
Insert(data,ha);
print(ha);
}