-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashTable.cpp
More file actions
109 lines (92 loc) · 2.41 KB
/
Copy pathHashTable.cpp
File metadata and controls
109 lines (92 loc) · 2.41 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
103
104
105
106
107
108
109
// HashTable.cpp
#include "HashTable.h"
#include <string.h>
// Node constructor
Node::Node(int val) : value(val), next(nullptr) {}
// LinkedList constructor
LinkedList::LinkedList() : head(nullptr) {}
// LinkedList destructor
LinkedList::~LinkedList() {
Node* current = head;
while (current != nullptr) {
Node* next = current->next;
delete current;
current = next;
}
}
// LinkedList method to add a value at the end
void LinkedList::push_back(int number) {
if (head == nullptr) {
head = new Node(number);
} else {
Node* current = head;
while (current->next != nullptr) {
current = current->next;
}
current->next = new Node(number);
}
}
// LinkedList method to check if a value exists
bool LinkedList::contains(int number) {
Node* current = head;
while (current != nullptr) {
if (current->value == number) {
return true;
}
current = current->next;
}
return false;
}
// HashTable constructor
HashTable::HashTable(int initialCapacity) : capacity(initialCapacity), currentSize(0) {
table = new LinkedList[capacity];
}
// HashTable destructor
HashTable::~HashTable() {
delete[] table;
}
// Hash function
int HashTable::hashFunction(int key) {
return key % capacity;
}
// Get the current size of the hash table
int HashTable::getSize() {
return currentSize;
}
// Search for a number in the hash table
char* HashTable::search(int number) {
int index = hashFunction(number);
if (table[index].contains(number)) {
return "SUCCESS";
}
return "FAILURE";
}
// Insert a number into the hash table
bool HashTable::insert(int number) {
if (strcmp(search(number), "SUCCESS") == 0) {
return false; // Number already exists
}
if (currentSize >= capacity * 0.7) {
rehash();
}
int index = hashFunction(number);
table[index].push_back(number);
currentSize++;
return true;
}
// Rehash the table when load factor is high
void HashTable::rehash() {
int oldCapacity = capacity;
capacity = 2 * capacity;
LinkedList* oldTable = table;
table = new LinkedList[capacity];
currentSize = 0;
for (int i = 0; i < oldCapacity; ++i) {
Node* current = oldTable[i].head;
while (current != nullptr) {
insert(current->value);
current = current->next;
}
}
delete[] oldTable;
}