forked from H0NEYP0T-466/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbucket_array.cpp
More file actions
102 lines (82 loc) · 2.47 KB
/
Copy pathbucket_array.cpp
File metadata and controls
102 lines (82 loc) · 2.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
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
#include <iostream>
#include <vector>
#include <list>
// Hash function (hashCode)
int hashCode(int key, int size) {
return key % size;
}
// Compression function (index calculation)
int compress(int code, int size) {
return code % size;
}
// Node structure for chaining
struct Node {
int key;
int value;
Node* next;
};
// Bucket array (hashmap)
class HashMap {
private:
int size;
std::vector<Node*> buckets;
public:
HashMap(int size) : size(size), buckets(size, nullptr) {}
// Insert key-value pair
void insert(int key, int value) {
int index = compress(hashCode(key, size), size);
Node* newNode = new Node{key, value, nullptr};
if (buckets[index] == nullptr) {
buckets[index] = newNode;
} else {
Node* current = buckets[index];
while (current->next != nullptr) {
current = current->next;
}
current->next = newNode;
}
}
// Search for key
int search(int key) {
int index = compress(hashCode(key, size), size);
Node* current = buckets[index];
while (current != nullptr) {
if (current->key == key) {
return current->value;
}
current = current->next;
}
return -1; // Key not found
}
// Delete key-value pair
void remove(int key) {
int index = compress(hashCode(key, size), size);
Node* current = buckets[index];
Node* previous = nullptr;
while (current != nullptr) {
if (current->key == key) {
if (previous == nullptr) {
buckets[index] = current->next;
} else {
previous->next = current->next;
}
delete current;
return;
}
previous = current;
current = current->next;
}
}
};
int main() {
HashMap hashmap(10);
hashmap.insert(1, 10);
hashmap.insert(2, 20);
hashmap.insert(11, 110); // Collision with key 1
std::cout << hashmap.search(1) << std::endl; // Output: 10
std::cout << hashmap.search(2) << std::endl; // Output: 20
std::cout << hashmap.search(11) << std::endl; // Output: 110
hashmap.remove(1);
std::cout << hashmap.search(1) << std::endl; // Output: -1 (Key not found)
return 0;
}