-
Notifications
You must be signed in to change notification settings - Fork 1
/
Hashmap.h
137 lines (134 loc) · 3.17 KB
/
Hashmap.h
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#include <cstring>
#include <iostream>
using namespace std;
#ifndef HASHMAP_H
#define HASHMAP_H
namespace hashing {
template<typename T>
class Node {
public:
string key;
T data;
Node<T>* next;
Node(string k, T d) {
key = k;
data = d;
next = NULL;
}
~Node() {
if(next!=NULL)
delete next;
}
};
}
template<typename T>
class hashmap {
hashing::Node<T>** buckets;
int ts;
int cs;
float lf;
int hashFn(string key) {
int p =1;
int ans = 0 ;
int l = key.length();
for(int i=0;i<l;i++) {
ans += key[l-i-1]*p;
p =(p*37)%ts;
}
return ans%ts;
}
void rehash() {
hashing::Node<T>** oldbuckets = buckets;
buckets = new hashing::Node<T>*[ts*2];
cs = 0;
ts = ts * 2;
for(int i=0;i<ts/2;i++)
{
hashing::Node<T>* temp = oldbuckets[i];
while(temp!=NULL) {
insert(temp->key, temp->data);
temp = temp->next;
}
delete oldbuckets[i];
}
delete [] oldbuckets;
}
public:
hashmap(int t=7) {
ts = t;
cs = 0 ;
lf = 0.7;
buckets = new hashing::Node<T>*[t];
}
hashmap(int t, float l=0.7) {
ts = t;
cs = 0 ;
lf = l ;
buckets = new hashing::Node<T>*[t];
}
void insert(string key, T value) {
int i = hashFn(key);
hashing::Node<T>* temp = buckets[i];
hashing::Node<T>* toInsert = new hashing::Node<T>(key,value);
toInsert->next = buckets[i];
buckets[i] = toInsert;
cs++;
lf = (float)cs/ts;
if(lf>0.7)
rehash();
}
T* find(string key) {
int i = hashFn(key);
hashing::Node<T>* temp = buckets[i];
while(temp!=NULL) {
if(!temp->key.compare(key))
return &temp->data;
temp = temp->next;
}
return NULL;
}
void print() {
for(int i=0;i<ts;i++) {
cout<<"Bucket "<<i<<"-> ";
hashing::Node<T>* temp = buckets[i];
while(temp!=NULL) {
cout<<temp->key<<"-> ";
temp = temp->next;
}
cout<<endl;
}
}
void erase(string key) {
int i = hashFn(key);
hashing::Node<T> *temp = buckets[i];
hashing::Node<T> *prev = buckets[i];
if(!temp->key.compare(key)){
/// If the hashing::Node to delete is head
buckets[i] = temp->next;
return ;
}
temp = temp->next;
while(temp!=NULL) {
if(!temp->key.compare(key) ){
prev->next = temp->next;
return;
}
prev = temp;
temp = temp->next;
}
}
T& operator[](string key) {
T* temp = find(key);
if(temp==NULL) {
/// create a new hashing::Node;
T empty;
insert(key, empty);
return *find(key);
}
else {
/// return reference
return *temp;
}
}
};
#endif