-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy path查找_哈希表(散列表)_.cpp
106 lines (99 loc) · 1.7 KB
/
查找_哈希表(散列表)_.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include <stdio.h>
#include <stdlib.h>
#define ElemType int
#define NULLKEY -1000
#define HASHSPACE 25
#define HASHSIZE 13
typedef struct
{
ElemType *elem;
int count;
int sizeindex;
}HashTable;
void Initial(HashTable &T)
{
T.elem=(ElemType*)malloc(HASHSPACE*sizeof(ElemType));
T.sizeindex=HASHSPACE;
T.count=0;
for (int i=0;i<HASHSPACE;i++)
{
T.elem[i]=NULLKEY;
}
}
int hash(int key)
{
return key%HASHSIZE;
}
int InsertTable(HashTable &T,int key)
{
int key_pos;
key_pos=hash(key);
if(T.count==T.sizeindex)
{
printf("space not enough\n");
return -1;
}
while(T.elem[key_pos]!=NULLKEY)
{
//key_pos=(++key_pos)%HASHSIZE;
key_pos=hash(++key_pos);
}
printf("--->%d %d\n",key_pos,key);
T.elem[key_pos]=key;
T.count++;
}
int DelNumTable(HashTable &T,int key)
{
int key_pos;
key_pos=hash(key);
while(T.elem[key_pos]!=NULLKEY)
{
if(T.elem[key_pos]==key)
{
printf("del->%d %d\n",key,key_pos);
T.elem[key_pos]=NULLKEY;
T.count--;
return 0;
}
else
{
key_pos=(++key_pos)%HASHSIZE;
}
}
printf("%d,not find,so not del\n",key);
return -1;
}
int SerachTable(HashTable &T,int key)
{
int key_pos;
key_pos=hash(key);
while(T.elem[key_pos]!=NULLKEY)
{
if(T.elem[key_pos]==key)
{
printf("find->%d %d\n",key,key_pos);
return 0;
}
else
{
key_pos=(++key_pos)%HASHSIZE;
}
}
printf("%d,not find\n",key);
return -1;
}
int main()
{
HashTable T;
int arr[]={5,21,34,8,6,32,48};
Initial(T);
for(int i=0;i<7;i++)
{
InsertTable(T,arr[i]);
}
SerachTable(T,21);
DelNumTable(T,6);
SerachTable(T,8);
printf("T->len=%d\n",T.count);
return 0;
}