-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchapter7-hash-map.cpp
142 lines (122 loc) · 2.38 KB
/
chapter7-hash-map.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
139
140
141
142
// My implementation for hash map.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class HashMap {
public:
HashMap() {
_buckets.resize(_bucket_num);
int i;
for (i = 0; i < _bucket_num; ++i) {
_buckets[i] = nullptr;
}
};
bool contains(int key) {
key = (key > 0) ? key : -key;
key = key % _bucket_num;
LinkedList *ptr = _buckets[key];
while (ptr != nullptr) {
if (ptr->key == key) {
return true;
}
}
return false;
};
int& operator [] (int key) {
key = (key > 0) ? key : -key;
key = key % _bucket_num;
LinkedList *ptr = _buckets[key];
if (ptr == nullptr) {
_buckets[key] = new LinkedList(key);
return _buckets[key]->val;
}
LinkedList *ptr2 = ptr->next;
if (ptr->key == key) {
return ptr->val;
}
while (ptr2 != nullptr) {
if (ptr2->key == key) {
return ptr2->val;
} else {
ptr = ptr->next;
ptr2 = ptr2->next;
}
}
ptr->next = new LinkedList(key);
ptr = ptr->next;
return ptr->val;
}
void erase(int key) {
key = (key > 0) ? key : -key;
key = key % _bucket_num;
LinkedList *ptr = _buckets[key];
if (ptr == nullptr) {
return;
} else if (ptr->next == nullptr) {
if (ptr->key == key) {
delete _buckets[key];
_buckets[key] = nullptr;
}
return;
}
if (ptr->key == key) {
_buckets[key] = ptr->next;
delete ptr;
return;
}
LinkedList *ptr2;
ptr2 = ptr->next;
while (ptr2 != nullptr) {
if (ptr2->key == key) {
ptr->next = ptr2->next;
delete ptr2;
return;
} else {
ptr = ptr->next;
ptr2 = ptr2->next;
}
}
}
~HashMap() {
int i;
LinkedList *ptr;
for (i = 0; i < _bucket_num; ++i) {
ptr = _buckets[i];
while (ptr != nullptr) {
ptr = ptr->next;
delete _buckets[i];
_buckets[i] = ptr;
}
}
_buckets.clear();
}
private:
struct LinkedList {
int key;
int val;
LinkedList *next;
LinkedList(int _key = 0, int _val = 0): key(_key), val(_val), next(nullptr) {};
};
static const int _bucket_num = 10000;
vector<LinkedList *> _buckets;
};
int main()
{
HashMap hm;
string cmd;
int op1, op2;
while (cin >> cmd) {
if (cmd == "set") {
cin >> op1 >> op2;
hm[op1] = op2;
} else if (cmd == "get") {
cin >> op1;
cout << hm[op1] << endl;
} else if (cmd == "find") {
cin >> op1;
cout << (hm.contains(op1) ? "true" : "false") << endl;
}
}
return 0;
}