1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4
5
6 typedef int ElementType;
7 typedef unsigned int Index;
8
9 struct ListNode;
10 typedef struct ListNode *Position;
11 struct HashTbl;
12 typedef struct HashTbl *HashTable;
13
14
15 Index Hash( const int Key, int TableSize);
16
17 HashTable InitializeTable( int TableSize );
18 void DestoryTable( HashTable H);
19 Position Find(ElementType Key, HashTable H);
20 void Insert( ElementType Key, HashTable H);
21 ElementType Retrieve( Position P);
22
23
24 #define MintableSize 10
25
26 typedef Position List;
27
28 struct ListNode
29 {
30 ElementType Element;
31 Position Next;
32 };
33
34 Index
35 Hash( const int Key, int TableSize)
36 {
37 return Key % TableSize;
38 }
39
40
41 struct HashTbl
42 {
43 int TableSize;
44 List *TheLists;
45 };
46
47 static int
48 NextPrime( int N)
49 {
50 int i;
51
52 if( N % 2 == 0)
53 N ++;
54 for( ; ; N += 2)
55 {
56 for( i =3; i*i < N; i +=2)
57 {
58 if( N % i == 0)
59 goto ContOuter;
60 return N;
61 }
62 ContOuter :;
63 }
64 }
65
66
67
68
69 HashTable
70 InitializeTable(int TableSize)
71 {
72 HashTable H;
73 int i;
74 if( TableSize < MintableSize )
75 {
76 printf("table size too small");
77 return NULL;
78 }
79
80 H = malloc(sizeof(struct HashTbl));
81 if( H == NULL)
82 printf("error ---");
83
84 H->TableSize = NextPrime( TableSize);
85
86 H->TheLists = malloc(sizeof(List) * H->TableSize);
87 if( H ->TheLists == NULL)
88 printf("out of space");
89
90 for( i = 0; i < H->TableSize; i++)
91 {
92 H->TheLists[i] = malloc(sizeof(struct ListNode));
93 if(H->TheLists[i] == NULL)
94 printf("out of space");
95 else
96 H->TheLists[i]->Next = NULL;
97 }
98 return H;
99 }
100
101
102 Position
103 Find(ElementType Key, HashTable H)
104 {
105 Position P;
106 List L;
107
108 L = H->TheLists[Hash( Key,H->TableSize)];
109 P = L->Next;
110
111 while( P != NULL && P->Element != Key)
112 {
113 P = P->Next;
114 }
115
116 return P;
117 }
118
119
120
121 void
122 Insert(ElementType Key, HashTable H)
123 {
124 Position Pos,NewCell;
125 List L;
126
127
128 Pos = Find(Key,H);
129 if( Pos = NULL)
130 {
131 NewCell = malloc(sizeof(struct ListNode));
132 if( NewCell == NULL)
133 printf("Error");
134
135 else
136 {
137 L = H->TheLists[ Hash( Key, H->TableSize)];
138 NewCell->Next = L->Next;
139 NewCell->Element = Key;
140 L->Next = NewCell;
141 }
142 }
143 }
144
145
146
147 void
148 DestoryTable( HashTable H)
149 {
150 int i;
151 for( i =0 ; i< H->TableSize; i++)
152 {
153 Position P = H->TheLists[i];
154 Position Tmp;
155
156 while( P != NULL)
157 {
158 Tmp = P->Next;
159 free(P);
160 P = Tmp;
161 }
162 }
163 free( H->TheLists);
164 free(H);
165 }
166
167 ElementType
168 Retrieve(Position P)
169 {
170 return P->Element;
171 }
172
173 int main()
174 {
175 HashTable H = InitializeTable( 10 );
176 int i;
177 printf( "HashTable:\n" );
178 for ( i = 1; i < 22; i++ )
179 {
180 Insert( i * i, H );
181 printf( "%d:%d\n", i*i, Hash( i * i, 10 ) );
182 }
183 return 0;
184 }