题目描述
采用除留余数法(H(key)=key %n)建立长度为n的哈希表,处理冲突用链地址法。建立链表的时候采用尾插法。
输入
第一行为哈西表的长度m;
第二行为关键字的个数n;
第三行为关键字集合;
第四行为要查找的数据。
输出
如果查找成功,输出该关键字所在哈希表中的地址和比较次数;如果查找不成功,输出-1。
样例输入
13
13
16 74 60 43 54 90 46 31 29 88 77 78 79
16
样例输出
3,1
参考程序
#include<stdio.h>
#include<stdlib.h>
#define max 60
typedef struct node
{
int num;
struct node *next;
}hash;
hash *ht[max];
int p,n;
void search(int key)
{
int k,c=1;
k=key%p;
hash *t;
t=ht[k];
while(t!=NULL&&t->num!=key)
{
c++;
t=t->next;
}
if(t==NULL)
{
printf("-1");
}
else
{
printf("%d,%d",k,c);
}
}
void create()
{
hash *t;
int i,j;
for(i=0;i<n;i++) ht[i]=NULL;
for(i=0;i<n;i++)
{
t=(hash *)malloc(sizeof(hash));
scanf("%d",&t->num);
j=t->num%p;
t->next=ht[j]; //将t结点插入到ht[j]之后;
ht[j]=t;
}
}
int main()
{
int k;
scanf("%d",&p);
scanf("%d",&n);
create();
scanf("%d",&k);
search(k);
return 0;
}
注意
该程序仅供学习参考!