forked from Minor-lazer/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHash Table Class Chaining.txt
104 lines (92 loc) · 1.74 KB
/
Hash Table Class Chaining.txt
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
#include <iostream>
using namespace std;
// Linked List node
class Node{
public:
int data;
Node* next;
};
// Hash Table
class HashTable{
public:
Node** HT;
HashTable();
int hash(int key);
void Insert(int key);
int Search(int key);
~HashTable();
};
HashTable::HashTable() {
HT = new Node* [10];
for (int i=0; i<10; i++){
HT[i] = nullptr;
}
}
int HashTable::hash(int key) {
return key % 10;
}
void HashTable::Insert(int key) {
int hIdx = hash(key);
Node* t = new Node;
t->data = key;
t->next = nullptr;
// Case: No nodes in the linked list
if (HT[hIdx] == nullptr){
HT[hIdx] = t;
} else {
Node* p = HT[hIdx];
Node *q=HT[hIdx];
// Traverse to find insert position
while (p && p->data < key){
q=p;
p = p->next;
}
// Case: insert position is first
if (q == HT[hIdx]){
t->next = HT[hIdx];
HT[hIdx] = t;
} else {
t->next = q->next;
q->next = t;
}
}
}
int HashTable::Search(int key) {
int hIdx = hash(key);
Node* p = HT[hIdx];
while (p){
if (p->data == key){
return p->data;
}
p = p->next;
}
return -1;
}
HashTable::~HashTable() {
for (int i=0; i<10; i++){
Node* p = HT[i];
while (HT[i]){
HT[i] = HT[i]->next;
delete p;
p = HT[i];
}
}
delete [] HT;
}
int main() {
int A[] = {16, 12, 25, 39, 6, 122, 5, 68, 75};
int n = sizeof(A)/sizeof(A[0]);
HashTable H;
for (int i=0; i<n; i++){
H.Insert(A[i]);
}
cout << "Successful Search" << endl;
int key = 6;
int value = H.Search(key);
cout << "Key: " << key << ", Value: " << value << endl;
cout << "Unsuccessful Search" << endl;
key = 95;
value = H.Search(key);
cout << "Key: " << key << ", Value: " << value << endl;
return 0;
}