-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHashTable.cpp
103 lines (94 loc) · 1.87 KB
/
HashTable.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
#include <iostream>
#include "HashTable.h"
int HashTable::hash(int key)
{
return key % BUCKET_SIZE;
}
void HashTable::Insert(int key, int value)
{
// TODO
int idx = hash(key);
HashNode* p = bucket.at(idx);
if(!p)
{
//add head node
bucket[idx] = new HashNode(key,value);
}
else
{
if(p->key == key)
{
p->val = value;
return;
}
while (p->next)
{
if(p->next->key==key)
{
p->next->val = value;
break;
}
p=p->next;
}
if(!p->next)
{
p->next = new HashNode(key,value);
}
}
}
void HashTable::Search(int key)
{
// TODO
int idx = hash(key);
HashNode* p = bucket.at(idx);
int count = 0;
while(p)
{
if(p->key==key)
{
std::cout<<"bucket "<<idx<<" index "<< count<<" key "<<key<<" value "<<p->val<<std::endl;
return;
}
p=p->next;
count++;
}
std::cout<<"Not Found"<<std::endl;
}
void HashTable::Delete(int key)
{
int idx = hash(key);
HashNode* p = bucket.at(idx);
if(!p)
return;
if(p->key==key)
{
bucket.at(idx) = p->next;
delete p;
return;
}
while (p->next)
{
if(p->next->key==key)
{
HashNode* tmp = p->next;
p->next = p->next->next;
delete tmp;
return;
}
p=p->next;
}
}
void HashTable::Display()
{
for (int i = 0; i < BUCKET_SIZE; ++i)
{
std::cout << "|Bucket " << i << "|";
HashNode *node = bucket[i];
while (node)
{
std::cout << "-->(" << node->key << "," << node->val << ")";
node = node->next;
}
std::cout << "-->" << std::endl;
}
}