#include<stdio.h>
#include<malloc.h>
#define keynum 32 //要存放的元素个数
//哈希结点
struct HashAddress
{
int key; //存放元素
int flag; // 是否存放元素标示
};
//哈希表初始化
void intailHash(HashAddress * wh,int n)
{
for(int i=0;i<n;i++)
wh[i].flag=-1;
}
//把元素放进哈希表中
//m n分别表示 哈希表长度,与元素规模通常m=2*n时,较合理
//这里哈希函数为KEY%m,解决冲突办法是+1
void CreatHash(HashAddress *wh,int m,int *A,int n)
{
int place;
for(int i=0;i<n;i++)
{
place=A[i]%m;
while(wh[place].flag!=-1) // 冲突
{
place=(place+1)%m;
}
wh[place].flag=1; // 元素放入哈希表
wh[place].key=A[i];
}
}
//在长为m哈希表中找元素KEY,找到输出其地址和查找次数
void FindKeyInHash(HashAddress *wh,int m,int key)
{
int place;
place=key%m;
int findtime=0;
while(wh[place].flag!=-1&&wh[place].key!=key)
{
place=(place+1)%m;
findtime++;
}
printf("found %dth \n",findtime);
if( wh[place].key==key) // 找到
{
printf("have the key %d \n",place);
return;
}
else if(wh[place].flag==-1)//找不到
{
printf("no the key!");
return;
}
}
int main()
{
int num[keynum]={15,16,26,75,18,25,27,1,2,9,28,29,19,20,21,22,23,24,30,31,32,10,11,12,13,3,4,5,6,7,8,14};//测试数据
HashAddress * where=(HashAddress*)malloc(sizeof(HashAddress)*2*keynum);
if(NULL==where)
{
printf("no memroy for hashaddress \n");
return -1;
}
intailHash(where,keynum*2);
CreatHash(where,2*keynum,num,keynum);
FindKeyInHash(where,2*keynum,75);
}