/* Note:Your choice is C IDE */
#include "stdio.h"
#define MAX 100
#define NULLKEY -1
/*定义空关键字值*/
#define DELKEY -2
/*定义被删关键字值*/
typedef int keytype;
typedef struct node
{
keytype key;
char data;
int count;
/*探查次数域*/
}HashTable[MAX];
void insertHT(HashTable ha,int n,keytype k,int p)
{
int i,adr;
adr=k%p;
if(ha[adr].key==NULLKEY || ha[adr].key==DELKEY)
{
ha[adr].key=k;
ha[adr].count=1;
}
else
{
i=1;
do
{
adr=(adr+1)%p;
i++;
}while(ha[adr].key!=NULLKEY && ha[adr].key!=DELKEY);
ha[adr].key=k;
ha[adr].count=i;
/*和冲突数据移动后的位置*/
}
n++;
}
void creatHT(HashTable ha,keytype x[],int n,int m,int p)
{
int i,n1=0;
for(i=0;i<m;i++)
{
ha[i].key=NULLKEY;
ha[i].count=0;
}
for(i=0;i<n;i++)
insertHT(ha,n1,x[i],p);
}
int searchHT(HashTable ha,int p,keytype k)
{
int i,adr;
adr=k%p;
while(ha[adr].key!=NULLKEY && ha[adr].key!=k)
{
i++;
adr=(adr+1)%p;
}
if(ha[adr].key==k)
return adr;
else return -1;
}
int deleteHT(HashTable ha,int p,int k,int n)
{
int adr;
adr=searchHT(ha,p,k);
if(adr!=-1)
{
ha[adr].key=DELKEY;
n--;
return 1;
}
else return 0;
}
void displayHT(HashTable ha,int n,int m)
{
int i;
printf("哈希表地址:\t");
for(i=0;i<m;i++)
printf("%3d",i);printf("\n");
printf("哈希表关键字:\t");
for(i=0;i<m;i++)
if(ha[i].key==NULLKEY || ha[i].key==DELKEY)
printf("
");
else
printf("%3d",ha[i].key);printf("\n");
printf("探查次数:\t");
for(i=0;i<m;i++)
if(ha[i].key==NULLKEY ||ha[i].key==DELKEY)
printf("
");
else
printf("%3d",ha[i].count);
}
void main()
{
int x[]={16,74,60,43,54,90,46,31,29,88,77};
int n=11,m=13,p=13,i,k=29;
HashTable ha;
creatHT(ha,x,n,m,p);
printf("\n");displayHT(ha,n,m);
i=searchHT(ha,p,k);
if(i!=-1)
printf("\nha[%d].key=%d\n",i,k);
else
printf("\n未找到%d\n",k);
k=77;
printf("删除关键字%d\n",k);
deleteHT(ha,p,k,n);
displayHT(ha,n,m);
i=searchHT(ha,p,k);
if(i!=-1)
printf("ha[%d].key=%d\n",i,k);
else
printf("\n未找到%d\n",k);
printf("插入关键字%d\n",k);
insertHT(ha,n,k,p);
displayHT(ha,n,m);printf("\n");
}