-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashmapDelete.cpp
More file actions
117 lines (103 loc) · 2.16 KB
/
HashmapDelete.cpp
File metadata and controls
117 lines (103 loc) · 2.16 KB
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
#include <string>
using namespace std;
template <typename V>
class MapNode {
public:
string key;
V value;
MapNode* next;
MapNode(string key, V value) {
this->key = key;
this->value = value;
next = NULL;
}
~MapNode() {
delete next;
}
};
template <typename V>
class ourmap {
MapNode<V>** buckets;
int count;
int numBuckets;
public:
ourmap() {
count = 0;
numBuckets = 5;
buckets = new MapNode<V>*[numBuckets];
for (int i = 0; i < numBuckets; i++) {
buckets[i] = NULL;
}
}
~ourmap() {
for (int i = 0; i < numBuckets; i++) {
delete buckets[i];
}
delete [] buckets;
}
int size() {
return count;
}
V getValue(string key) {
int bucketIndex = getBucketIndex(string key);
MapNode<V>* head = buckets[bucketIndex];
while (head != NULL) {
if (head->key == key) {
return head->value;
}
head = head->next;
}
return 0;
}
private:
int getBucketIndex(string key) {
int hashCode = 0;
int currentCoeff = 1;
for (int i = key.length() - 1; i >= 0; i--) {
hashCode += key[i] * currentCoeff;
hashCode = hashCode % numBuckets;
currentCoeff *= 37;
currentCoeff = currentCoeff % numBuckets;
}
return hashCode % numBuckets;
}
public:
void insert(string key, V value) {
int bucketIndex = getBucketIndex(string key);
MapNode<V>* head = buckets[bucketIndex];
while (head != NULL) {
if (head->key == key) {
head->value = value;
return;
}
head = head->next;
}
head = buckets[bucketIndex];
MapNode<V>* node = new MapNode<V>(key, value);
node->next = head;
buckets[bucketIndex] = node;
count++;
}
V remove(string key) {
int bucketIndex = getBucketIndex(string key);
MapNode<V>* head = buckets[bucketIndex];
MapNode<V>* prev = NULL;
while (head != NULL) {
if (head->key == key) {
if (prev == NULL) {
buckets[bucketIndex] = head->next;
} else {
prev->next = head->next;
}
V value = head->value;
head->next = NULL;
delete head;
count--;
return value;
}
prev = head;
head = head->next;
}
return 0;
}
};