-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathHashSet.cpp
More file actions
104 lines (92 loc) · 2.55 KB
/
HashSet.cpp
File metadata and controls
104 lines (92 loc) · 2.55 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
#include <cstdlib>
#include <iostream>
#include "HashSet.h"
using namespace std;
// Initialize our member variables in the constructor
HashSet::HashSet(int capacity, int method) {
this->capacity = capacity;
this->method = method;
mysize = 0;
elements = new HashNode*[capacity](); // all are initialized to nullptr using ()
}
int HashSet::hash(int value) const {
return abs(value) % capacity;
}
// Private helper for calculating the bucket of a given a value
int HashSet::getIndexOf(int value) const {
return hash(value) % capacity;
}
void HashSet::add(int value) {
if (!contains(value)) {
int bucket = getIndexOf(value);
// insert at the front of the list in that bucket
elements[bucket] = new HashNode{value, elements[bucket]};
mysize++;
}
if (mysize / capacity >= 2) {
rehash();
}
}
bool HashSet::contains(int value) const {
HashNode* curr = elements[getIndexOf(value)];
while (curr != nullptr) {
if (curr->data == value) {
return true;
}
curr = curr->next;
}
return false;
}
HashSet::~HashSet() {
clear(); // Remove all elements
delete[] elements; // Also delete the array itself
}
// Remove all elements in our set so all buckets in our array are nullptr
void HashSet::clear() {
for (int i = 0; i < capacity; i++) {
// free list in bucket i
while (elements[i] != nullptr) {
HashNode* curListNode = elements[i];
elements[i] = elements[i]->next;
delete curListNode;
}
}
mysize = 0;
}
void HashSet::rehash() {
HashNode** oldElements = elements;
int oldCapacity = capacity;
capacity *= 2;
elements = new HashNode*[capacity]();
for (int i = 0; i < oldCapacity; i++) {
HashNode* curr = oldElements[i];
while (curr != nullptr) { // iterate over old bucket
HashNode* prev = curr;
curr = curr->next; // don’t lose access to rest of old bucket
int newBucket = getIndexOf(prev->data);
prev->next = elements[newBucket]; // put prev node at front of new bucket
elements[newBucket] = prev; // update new bucket pointer
}
}
delete[] oldElements;
}
void HashSet::printBucket(int value) {
int bucket = getIndexOf(value);
HashNode* curr = elements[bucket];
while (curr != nullptr) {
cout << curr->data << " -> ";
curr = curr->next;
}
cout << "nullptr" << endl;
}
void HashSet::printHashSet() {
for (int i = 0; i < capacity; i++) {
cout << "Bucket " << i << ": ";
HashNode* curr = elements[i];
while (curr != nullptr) {
cout << curr->data << " -> ";
curr = curr->next;
}
cout << "nullptr" << endl;
}
}