链地址法

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct Node{
char key[200];
char value[200];
Node *next;
}Node;
unsigned int BKDRHash(char *str,int Hash_Size)//unsigned?
{
unsigned int seed = 31; // 31 131 1313 13131 131313 etc…
unsigned int hash = 0;

while (*str)
{
    hash = (hash * seed + (*str++))% Hash_Size;
}

return (hash% Hash_Size); //使hash函数返回值在hash表的有效地址范围

}
void insert(char key[],Node &node,int n)
{
Node *p=&node;
while(p->key[0]!=0)
{
p=p->next;
}
int k=BKDRHash(key,n);
memset(p->key,’\0’,200);
memset(p->key,’\0’,200);
strcpy(p->key,key);
scanf("%s",p->value);
Node *tail=(Node *)malloc(sizeof(Node));
memset(tail->key,0,200);
p->next=tail;
tail->next=NULL;
}
void show(Node node[],int n)
{
int i;
for(i=0;i<n;i++)
{
printf("%s %s\n",node[i].key,node[i].value);
Node *p=&node[i];
if(!p->next)//避开空结点
continue;
p=p->next;
while(p->key[0]!=0)
{
printf("%s %s\n",p->key,p->value);
p=p->next;
}
}
}
void init(Node node[],int m,int n)
{
for(int i=0;i<m;i++)
{
char key[200]={’\0’};
scanf("%s",key);
insert(key,node[BKDRHash(key,n)],n);
}
}
void find(Node node[],int n)
{
char temp[200]={’\0’};
scanf("%s",temp);
int i=BKDRHash(temp,n);
printf("%d “,i);
Node *p=&node[i];
while(p->key[0]!=0)
{
printf(”%s “,p->key);
if(!strcmp(p->key,temp))
{
printf(”%s",p->value);
break;
}
p=p->next;
}
if(p->key[0]==0)
{
printf(“NULL”);
}
}
void insert(Node node[],int n)
{
char temp[200]={’\0’};
scanf("%s",temp);
int i=BKDRHash(temp,n);
Node *p=&node[i];
if(!p->next)
{
strcpy(p->key,temp);
scanf("%s",p->value);
}
else
{
while(p->key[0]!=0)
{
p=p->next;
}
memset(p->key,’\0’,200);
memset(p->value,’\0’,200);
strcpy(p->key,temp);
scanf("%s",p->value);
}
Node *tail=(Node *)malloc(sizeof(Node));
memset(tail->key,’\0’,200);
p->next=tail;
tail->next=NULL;
printf("%d\n",i);
}
void desert(Node node[],int n)
{
char temp[200]={’\0’};
scanf("%s",temp);
int i=BKDRHash(temp,n);
printf("%d “,i);
Node *p=&node[i];
if(!p->next)
{
if(!strcmp(temp,p->key))
{
printf(”%s “,temp);
memset(p->key,’\0’,200);
memset(p->value,’\0’,200);
}
else
{
printf(”%s NULL\n",temp);
}
}
else
{
Node *p1=&node[i];
p=p->next;
while(p->key[0]!=0)
{
printf("%s “,p1->key);
if(!strcmp(p->key,temp))
{
printf(”%s",p->key);
p1->next=p->next;
Node *temp=p;
p=p->next;
free(temp);
printf("\n");
return;
}
p=p->next;
p1=p1->next;
}
if(p->key[0]==0)
{
printf("%s %s",p1->key,temp);
printf(“NULL\n”);
}
}

}
int main()
{
int i,n,m;
scanf("%d %d",&n,&m);
Node node[n]={0};
init(node,m,n);
insert(node,n);
desert(node,n);
find(node,n);
//show(node,n);
return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值