-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashMap.cpp
More file actions
36 lines (32 loc) · 1 KB
/
Copy pathHashMap.cpp
File metadata and controls
36 lines (32 loc) · 1 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
#include "hashmap.hpp"
#include <vector>
using namespace std;
Hashmap::Hashmap(int tableSize) : tableSize(tableSize) {
table.resize(tableSize, nullptr);
}
int Hashmap::hashFunction(int key) {
return key % tableSize;
}
void Hashmap::insert(int key, TreeNode* value) {
int index = hashFunction(key);
HashNode* newNode = new HashNode(key, value);
if (!table[index]) {
table[index] = newNode;
} else {
HashNode* current = table[index];
while (current->next) {
if (current->key == key) {
current->value = value; // Update existing key
delete newNode; // Avoid memory leak
return;
}
current = current->next;
}
if (current->key == key) {
current->value = value; // Update existing key
delete newNode; // Avoid memory leak
} else {
current->next = newNode; // Insert at end of chain
}
}
}