以下是以链表方式解决冲突问题,还有一种类似方法为哈希桶的方法,固定桶的个数以及桶的大小,这样可以计算查找的时间复杂度为o(1)+o(m),m为桶的大小
typedef struct hash_node
{
int key;
string value;
hash_node* next;
}*hash_node_ptr,link_node;//哈希元素
typedef struct hash_head_
{
hash_node_ptr next;
}hash_head,*hash_head_ptr;//头结点
hash_head_ptr HASH_TABLE[HASH_SIZE];//哈希表
hash_node_ptr init_hash_head()
{
hash_head_ptr p=(hash_head_ptr)malloc(sizeof(hash_head));
return p;
}
hash_node_ptr init_hash_node()
{
hash_node_ptr p=(hash_node_ptr)malloc(sizeof(hash_node));
if(!p)
return NULL;
return p;
}
void hash_table_init(hash_head_ptr HASH_TABLE[],int HASH_SIZE)//初始化哈希表
{
int i=0;
for(i;i<HASH_SIZE;i++)
{
HASH_TABLE[i]=init_hash_head();
HASH_TABLE[i].next=NULL;
}
return;
}
int hash_func(hash_node_ptr x)
{
int i=(x->key)%HASH_SIZE;
return i;
}
int hash_insert(hash_head_ptr HASH_TABLE[],hash_node_ptr x)//插入
{
if(!x)
return -1;
int pos=0;
pos=hash_func(x);
if(HASH_TABLE[i].next==NULL)
{
HASH_TABLE[i].next=x;
return 0;
}
hash_node_ptr p=HASH[i].next;
while(p->next!=NULL)
{
p=p->next;
}
p->next=x;
return 0;
}
int hash_find(hash_head_ptr HASH_TABLE,hash_node_ptr x)//查找
{
if(!x)
return -1;
int pos=hash_func(x);
if(HASH_TABLE[pos]->next==NULL)
return -1;
hash_node_ptr p=HASH_TABLE[pos]->next;
while(!p)
{
if(p->key==x->key)
{
return 0;
}
}
return -1;
}