-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashtable_Chaining_ADT
More file actions
98 lines (82 loc) · 2.05 KB
/
Hashtable_Chaining_ADT
File metadata and controls
98 lines (82 loc) · 2.05 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
#include <iostream>
#include <list>
int hash(int key, int size) {
return key % size;
}
template <typename K, typename V>
class Chaining {
private:
std::list<std::pair<K, V>>* ptr; // Array of lists (buckets)
int size;
public:
// Constructor
Chaining(int s = 10) {
this->size = s;
ptr = new std::list<std::pair<K, V>>[this->size];
}
// Destructor
~Chaining() {
delete[] ptr;
}
// Insert a key-value pair
void insert(K key, V val) {
std::pair<K, V> p;
p.first = key;
p.second = val;
int idx = hash(key, size);
ptr[idx].push_back(p);
}
// Erase a key-value pair
void erase(K key) {
int idx = hash(key, size);
typename std::list<std::pair<K, V>>::iterator it;
for (it = ptr[idx].begin(); it != ptr[idx].end(); ++it) {
if (it->first == key) {
ptr[idx].erase(it);
return;
}
}
std::cout << "Key " << key << " not found.\n";
}
// Find a value by key
void find(K key) {
int idx = hash(key, size);
typename std::list<std::pair<K, V>>::const_iterator it;
for (it = ptr[idx].begin(); it != ptr[idx].end(); ++it) {
if (it->first == key) {
std::cout << "Key: " << key << ", Value: " << it->second << "\n";
return;
}
}
std::cout << "Key " << key << " not found.\n";
}
// Display the hash table
void display() const {
for (int i = 0; i < size; ++i) {
std::cout << "Bucket " << i << ": ";
typename std::list<std::pair<K, V>>::const_iterator it;
for (it = ptr[i].begin(); it != ptr[i].end(); ++it) {
std::cout << "(" << it->first << ", " << it->second << ") ";
}
std::cout << "\n";
}
}
};
int main() {
Chaining<int, std::string> hashTable(5);
hashTable.insert(1, "One");
hashTable.insert(6, "Six");
hashTable.insert(11, "Eleven");
hashTable.insert(2, "Two");
std::cout << "Hash Table Contents:\n";
hashTable.display();
std::cout << "\nFinding key 6:\n";
hashTable.find(6);
std::cout << "\nErasing key 6:\n";
hashTable.erase(6);
std::cout << "\nHash Table After Erase:\n";
hashTable.display();
std::cout << "\nFinding key 6 after erase:\n";
hashTable.find(6);
return 0;
}