-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashTable.cpp
More file actions
115 lines (87 loc) · 2.18 KB
/
HashTable.cpp
File metadata and controls
115 lines (87 loc) · 2.18 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
#include "HashTable.h"
using namespace std;
HashTable::HashTable(int size, int (*getHash) (const string&)) {
this->size = size;
this->getHash = getHash;
table = new Node*[size];
for (int i = 0; i < size; i++) {
table[i] = nullptr;
}
}
void HashTable::Print() const {
for (int i = 0; i < size; i++) {
if (!table[i])
continue;
cout << "[" << i << "]:";
Node* tmp = table[i];
while (tmp) {
cout << " " << tmp->value;
tmp = tmp->next;
}
cout << endl;
}
}
// вставка элемента
void HashTable::Insert(const string& key, int value) {
int index = getHash(key); // находим индекс для вствки
// создаём указатель на элемнет
Node* node = new Node;
node->value = value;
node->next = nullptr;
// если ещё нет элементов в списке, то вставляем его и выходим
if (!table[index]) {
table[index] = node;
return;
}
Node* tmp = table[index]; // элемент для поиска конца списка
// ищем конец списка
while (tmp->next) {
tmp = tmp->next;
}
tmp->next = node; // добавляем элемент в конец
}
void HashTable::Remove(const string& key) {
int index = getHash(key); // находим индекс для удаления
while (table[index]) {
Node* tmp = table[index];
table[index] = table[index]->next;
delete tmp;
}
}
void HashTable::Search(const string& key) const {
int index = getHash(key); // находим индекс
Node* tmp = table[index];
if (!tmp) {
cout << "No values for key '" << key << "'" << endl;
return;
}
while (tmp) {
cout << tmp->value << " ";
tmp = tmp->next;
}
}
void HashTable::SaveInfo(const string& path) const {
ofstream f(path.c_str());
if (!f)
throw string("HashTable::SaveInfo: error open file.");
for (int i = 0; i < size; i++) {
int count = 0;
Node* tmp = table[i];
while (tmp) {
count++;
tmp = tmp->next;
}
f << count << endl;
}
f.close();
}
HashTable::~HashTable() {
for (int i = 0; i < size; i++) {
while (table[i]) {
Node* tmp = table[i];
table[i] = table[i]->next;
delete tmp;
}
}
delete[] table;
}