-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashTable.cpp
More file actions
66 lines (58 loc) · 1.39 KB
/
HashTable.cpp
File metadata and controls
66 lines (58 loc) · 1.39 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
class HashEntry {
public:
HashEntry(int key, int value) {
this->key = key;
this->value = value;
}
int getKey() {
return key;
}
int getValue() {
return value;
}
private:
int key, value;
};
const static int TABLE_SIZE = 128;
class HashTable {
public:
HashTable() {
table = new HashEntry *[TABLE_SIZE];
for(int i=0;i<TABLE_SIZE;++i) {
table[i] = nullptr;
}
}
int get(int key) {
int hash = key % TABLE_SIZE;
while (table[hash] && table[hash]->getKey() != key) {
hash = (hash + 1) % TABLE_SIZE;
}
if(table[hash] == nullptr) return -1;
else return table[hash]->getValue();
}
void set(int key, int value) {
int hash = key % TABLE_SIZE;
while (table[hash] && table[hash]->getKey() != key) {
hash = (hash + 1) % TABLE_SIZE;
}
if(table[hash])
delete table[hash];
table[hash] = new HashEntry(key, value);
}
~HashTable() {
for(int i=0;i<TABLE_SIZE;++i) {
if(table[i])
delete table[i];
}
delete [] table;
}
private:
HashEntry **table;
};
int main(int argc, const char * argv[]) {
HashTable *t = new HashTable();
t->set(1, 2);
t->set(3, 4);
std::cout << t->get(1) << "\n";
return 0;
}