#include <stdio.h>
#include <stdlib.h>
#define NULLKEY -32768
typedef struct
{
int *addr;
int len; // 当前数据元素个数
}hashtable;
//typedef struct hashnode *hashtable;
int m; //总表长 全局变量
int init_hashtable(hashtable *H)//不是查找表,改变了表,就要用指针
{
int i;
m =12;
H->len = m;
H->addr = (int *)malloc(m*sizeof(int));
for(i=0;i<m;i++)
H->addr[i] = NULLKEY;
return 1;
}
int hash(int key)
{
return key%m; //除留余数法
}
int insert_talble(hashtable *H,int key)
{
int i;
if(H->len=0) return 0;
int value = hash(key);
while(H->addr[value]!=NULLKEY)//不为空 冲突了
value = (value+1)%m; //开放定址法解决冲突
H->addr[value] = key;
return 1;
}
int search_table(hashtable H,int key)
{
int i;
if(H.len=0) return 0;
int value = hash(key);
while(H.addr[value]!=key && H.addr[value]!=NULLKEY)//不是要找的值,或者存了个别的比如16冲突的值
{
value = (value+1)%m; //开放定址法解决冲突
if(H.addr[value] == NULLKEY || value==hash(key))
{
printf("find fail %d!\n",key);
return 0;
}
}
printf("find and the addr is:%d.\n",value);
}
void print_hashtable(hashtable H)
{
int i;
for(i=0;i<m;i++)
printf("%6d",H.addr[i]);
printf("\n");
}
int main()
{
hashtable H;
init_hashtable(&H);
insert_talble(&H,24);
print_hashtable(H);
insert_talble(&H,2);
print_hashtable(H);
insert_talble(&H,4);
print_hashtable(H);
insert_talble(&H,12);
print_hashtable(H);
search_table(H,4);
search_table(H,16);
return 0;
}