哈斯一般用开放地址和拉链法来实现,开放地址的最坏情况要比拉链的可能性大,我的理解是开放地址形成冲突都是往后退然后放,
有可能形成要遍历全部数据才能找到要找的数据,而拉链的情况下一般来说,不会导致所有数据都同一条链表上。
至于平均复杂度,我不是很会分析,谁懂告诉我吧 :)
开放地址的源码:http://blog.csdn.net/kangquan2008/article/details/6772103
拉链法源码:
/********************************
*
* 哈斯拉链法
* author:huangkq1989
* blog: http://blog.csdn.net/kangquan2008
*
*******************************/
#include <stdio.h>
#include <stdlib.h>
#define HASH_SIZE 11
#define TYPE int
#define hash(data) \
(data)%HASH_SIZE
typedef struct Node
{
TYPE data;
struct Node * next;
}Node;
Node * node[HASH_SIZE];
void insert(TYPE data)
{
int index = hash(data);
Node * new_node = malloc(sizeof(Node));
if(new_node == NULL)
printf("memory alloc error"),exit(EXIT_FAILURE);
new_node->data = data;
new_node->next = NULL;
if(node[index] != NULL)
new_node->next = node[index];
node[index] = new_node;
}
Node* find(TYPE data)
{
int index = hash(data);
Node * p = node[index];
while(p)
{
if(p->data == data)
return p;
p = p->next;
}
return NULL;
}
// 统计出现的次数
int count_appearanc_times(TYPE data)
{
int cnt = 0;
int index = hash(data);
Node * p = node[index];
while(p)
{
if(p->data == data)
cnt ++;
p = p->next;
}
return cnt;
}
int main()
{
TYPE data[] = {1,1,1,1,1,1,2,3123,4,2131,45,123,43543,6,1323,65,
66,7,6,76,8,127,48,237,623,96,2212,224,213,1224,234,1221,143,11,23,13111,311};
for(int i=0; i<sizeof(data)/sizeof(data[0]); i++)
insert(data[i]);
while(1)
{
printf("input your choice:1 for find,2 for count\n");
int choice;
scanf("%d",&choice);
switch(choice)
{
case 1:
{
printf("input the data you want to find:\n");
TYPE target;
scanf("%d",&target);
if(find(target))
printf("Got it: %d\n",target);
else
printf("Not found :(\n");
break;
}
case 2:
{
printf("input the data you want to count:\n");
TYPE target;
scanf("%d",&target);
int times;
if(times = count_appearanc_times(target))
printf("Times of appearance: %d\n",times);
else
printf("Not found :(\n");
break;
}
default:
break;
}
}
return 0;
}