c语言构建哈希表

/*哈希查找
*哈希函数的构造方法常用的有5种。分别是:
*数字分析法
*平方取中法
*分段叠加
*伪随机数
*除留取余法
*这里面除留取余法比较常用
*避免哈希冲突常用的方法有4种:
*开放定址法(线性探测再散列、二次探测再散列)
*链地址法
*再哈希法
*建立公共溢出区
其中,线性探测再散列比较常用*/
 

这是一道2009年武汉科技大学的考研题,但是按照要求却做不出来,因为对7取模最多只有7个空间,不可能放进8个数,所以怀疑这道题是不是出错了,但这是考研题,应该不会出错吧。所以各位大神,你们怎么看?

以下是这道题的代码实现,可以看到27放不进哈希表中,因为哈希表已满!

 
 1 #include <stdio.h>
 2 #include <time.h>
 3 #define Max 7
 4 #define Length 10
 5 #define N 8
 6 
 7 int hashtable[Length];
 8 
 9 int func(int value)
10 {
11     return value % Max;
12 
13 }
14 
15 
16 void create_hash(int key)
17 {
18     int pos, t;
19     pos = func(key);
20     printf(" %d   MOD %d = %d\n", key, Max, pos);
21     t = pos;
22     while(hashtable[t] != -1)
23     {
24         printf("(%d+1) MOD %d = %d\n", t, Max, (t+1) % Max);
25         t = (t+1) % Max;
26         
27         if(pos == t)
28         {
29             
30             printf("Hash table is full!\n");
31             return;
32         }
33 
34     }
35     hashtable[t] = key;
36 
37 }
38 
39 main()
40 {
41     int flag[N] = {75, 33, 52, 41, 12, 88, 66, 27};
42     int i, j, t;
43     for(i = 0; i < Length; i++)
44         hashtable[i] = -1;
45 
46     i = 0;
47     while(i != N)
48     {
49         t = flag[i];
50         
51             create_hash(t);
52             printf("    ------------------------------------------------------------\n");
53             printf("    |  0 ||  1 ||  2 ||  3 ||  4 ||  5 ||  6 ||  7 ||  8 ||  9 |\n");
54             printf("    ------------------------------------------------------------\n");
55             printf("%2d: ", t);
56             for(j = 0; j < Length; j++)
57                 printf("| %2d |", hashtable[j]);
58 
59             printf("\n");
60             printf("    ------------------------------------------------------------\n");
61             
62             i++;
63         
64 
65     }
66     
67 }

运行结果:

猜你喜欢

转载自www.cnblogs.com/junsircoding/p/hashmap.html
今日推荐