-
Notifications
You must be signed in to change notification settings - Fork 0
/
HashTable_Direct.cpp
138 lines (124 loc) · 2.1 KB
/
HashTable_Direct.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
#include <iostream>
using namespace std;
#define MAX 100
struct Node
{
int info;
struct Node *pNext;
};
typedef struct Node *HashTable[MAX];
void CreateHashTable(HashTable &HT)
{
for (int i = 0; i < MAX; i++)
HT[i] = NULL;
}
int Hash(int x)
{
return x % MAX;
}
Node *CreateNode(int x)
{
Node *p = new Node;
if (p == NULL)
return NULL;
p->info = x;
p->pNext = NULL;
return p;
}
void AddTail(Node *&l, int k)
{
Node *p = CreateNode(k);
if (l == NULL)
{
l = p;
}
else
{
Node *q = l;
while (q->pNext != NULL)
q = q->pNext;
q->pNext = p;
}
}
void InsertNode(HashTable &HT, int x)
{
int index = Hash(x);
AddTail(HT[index], x);
}
Node *SearchNode(HashTable HT, int x)
{
int index = Hash(x);
Node *p = HT[index];
while (p != NULL)
{
if (p->info == x)
return p;
p = p->pNext;
}
return NULL;
}
void DeleteHead(Node *&l)
{
if (l != NULL)
{
Node *p = l;
l = l->pNext;
delete p;
}
}
void DeleteAfter(Node *&q)
{
Node *p = q->pNext;
if (p != NULL)
{
q->pNext = p->pNext;
delete p;
}
}
void DeleteNode(HashTable &HT, int x)
{
int index = Hash(x);
Node *p = HT[index];
Node *q = p;
while (p != NULL && p->info != x)
{
q = p;
p = p->pNext;
}
if (p == HT[index])
DeleteHead(HT[index]);
else
DeleteAfter(q);
}
void PrintHashTable(HashTable HT)
{
for (int i = 0; i < MAX; i++)
{
Node *p = HT[i];
cout << "HT[" << i << "]: ";
while (p != NULL)
{
cout << p->info << " ";
p = p->pNext;
}
cout << endl;
}
}
int main()
{
HashTable HT;
CreateHashTable(HT);
InsertNode(HT, 1);
InsertNode(HT, 2);
InsertNode(HT, 3);
InsertNode(HT, 4);
InsertNode(HT, 5);
InsertNode(HT, 6);
InsertNode(HT, 7);
PrintHashTable(HT);
DeleteNode(HT, 1);
DeleteNode(HT, 2);
DeleteNode(HT, 3);
PrintHashTable(HT);
return 0;
}