字符串 hash算法times33据说很经典,也很简单,就是不断的乘33,nHash = nHash*33 + *key++,没找到什么资料说这个比较好的理由,自己做了个测试,不多说,代码如下,测试环境win32 vc2008
hashmap.h
hashmap.c
p = map->hash_list[hash_key];
q = map->hash_list[hash_key];
if(hash_key>map->size || 0==p)
return -1;
while(p)
{
if(map->hash_cmp(p->key, key))
{
if(p != q)
q->next = p->next;
free(p);
p = 0;
}
q = p;
p = p->next;
}
return 0;
}
void* hash_value(struct hash_map *map, void *key)
{
int hash_key = map->hash_key(key)%map->size;
struct hash_node *p = map->hash_list[hash_key];
if(hash_key>map->size || 0==p)
return 0;
while(p)
{
if(map->hash_cmp(p->key, key))
return p->data;
p = p->next;
}
return 0;
}
void hash_destroy(struct hash_map *map)
{
int i = 0;
struct hash_node *p;
struct hash_node *q;
while(i<map->size)
{
p = map->hash_list[i];
if(p)
{
while(p)
{ q = p;
p = p->next;
free(q);
}
}
i++;
}
free(map->hash_list);
free(map);
return;
}
void hash_print(struct hash_map *map)
{
int i = 0;
int count = 0;
struct hash_node *p;
while(i < map->size)
{
p = map->hash_list[i];
while(p)
{
count++;
p = p->next;
}
printf("node %d = %d/n",i, count);
count = 0;
i++;
}
}
testhashmap.cpp
通过打印每个节点的字符串个数,显示分布还是比较平衡的