-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhashTable.cpp
More file actions
63 lines (40 loc) · 1.47 KB
/
hashTable.cpp
File metadata and controls
63 lines (40 loc) · 1.47 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
#include "hashTable.h"
int HashTable::defaultHashFunction(uintptr_t key){
return (unsigned)( key % ARRAY_SIZE );
}
void HashTable::store(uintptr_t key, PageListNode *value) {
int index = hashFunction(key);
HashEntry *hashEntry = new HashEntry(key, value);
if (array[index] == nullptr){ // no conflicts
array[index] = hashEntry;
}else{ // conflicts -> insert to front and link with previous first
HashEntry *copy = array[index];
hashEntry->next = copy;
copy->prev = hashEntry;
array[index] = hashEntry;
}
}
PageListNode *HashTable::get(uintptr_t key) {
long index = hashFunction(key);
HashEntry *hashEntry = array[index];
if (hashEntry == nullptr) return nullptr; // not stored
while (hashEntry != nullptr){ // traverse the list of conflicts to find it
if (hashEntry->key == key){ // bingo!
return hashEntry->node;
}
hashEntry = hashEntry->next; // check next node
}
return nullptr; // tough luck
}
HashTable::HashTable() {
for (int i=0; i<ARRAY_SIZE; i++){ // initialize to NULL for easier check for conflicts
this->array[i] = nullptr;
}
this->hashFunction = defaultHashFunction; // use that hashFunction
}
HashTable::HashTable(int (*customHashFunction)(uintptr_t)) { // -- NEVER USED --
for (int i=0; i<ARRAY_SIZE; i++){
this->array[i] = nullptr;
}
this->hashFunction = customHashFunction; // use a custom hash function
}