-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhashtable.cpp
More file actions
122 lines (97 loc) · 2.16 KB
/
Copy pathhashtable.cpp
File metadata and controls
122 lines (97 loc) · 2.16 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
110
111
112
113
114
115
116
117
118
119
120
121
#include <iostream>
#include <cmath>
using namespace std;
class Node {
public:
string key, value;
Node* next;
Node(string a, string b) {
key = a;
value = b;
next = NULL;
}
};
class LinkedList {
public:
Node* start;
int insertData(string key, string value){
Node* node_last = start;
Node* node_temp = start;
while (node_temp != NULL && node_temp->key != key) {
node_last = node_temp;
node_temp = node_temp->next;
}
node_last->next = new Node(key, value);
if (node_temp != NULL) {
node_last->next->next = node_temp->next;
delete node_temp;
}
return(1);
}
void dump() {
Node* current = start;
while (current->next != NULL) {
current = current->next;
cout << "\nCurrent key " << current->key << " with value " << current->value << "\n";
}
}
string getData(string keyToGet) {
Node* current = start;
while (current->next != NULL) {
current = current->next;
if (current->key == keyToGet) {
return(current->value);
}
}
return("Could not find");
}
LinkedList() {
start = new Node("head", "");
}
};
class Hashtable {
public:
LinkedList* table;
int hash_size;
int hash(string key) {
int hash_value = 0;
for (int i = 0; i < key.length(); i++)
hash_value += key[i];
return hash_value % hash_size;
}
int insertData(string key, string value) {
int hash_value = hash(key);
table[hash_value].insertData(key, value);
return 1;
}
string getData(string key) {
int hash_value = hash(key);
return(table[hash_value].getData(key));
}
void dump(string key) {
int hash_value = hash(key);
table[hash_value].dump();
}
Hashtable(int size) {
table = new LinkedList[size];
hash_size = size;
}
~Hashtable() {
delete [] table;
}
};
int main() {
Hashtable test(3);
test.insertData("testdfsersdf", "womp");
test.insertData("dffd", "tim");
test.insertData("dff", "PLO");
test.insertData("testdfsdfsersdf", "123");
test.insertData("fsda", "321");
test.insertData("testdfsersdf", "3233");
test.insertData("wer", "1");
test.insertData("tre", "2");
test.insertData("dff", "PLO2");
test.dump("testdfsersdf");
cout << "\n\n\n\n" << test.getData("dff");
return 0;
}