-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSeparateChainingHashTable.cpp
64 lines (57 loc) · 1.44 KB
/
SeparateChainingHashTable.cpp
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
#include "SeparateChainingHashTable.h"
#include "SinglelyLinkedList.h"
#include "DataStructAndAlgorithm.h"
SeparateChainingHashTable::SeparateChainingHashTable(int size) {
capacity = size;
data = new SinglelyLinkedList[size];
}
SeparateChainingHashTable::~SeparateChainingHashTable() {
delete[] data;
}
int SeparateChainingHashTable::hash(int element) {
return element % capacity;
}
bool SeparateChainingHashTable::search(int element,int &pos) {
pos = hash(element);
SinglelyLinkedList &list = data[pos];
for (LinkedListNode *node = list.head; node != nullptr; node = node->next) {
if (node->data == element) {
return true;
}
}
return false;
}
int SeparateChainingHashTable::insert(int element) {
int pos;
if (search(element, pos)) {
return pos;
}
else
{
LinkedListNode *node = new LinkedListNode(element);
pos = hash(element);
SinglelyLinkedList &list = data[pos];
if (list.head == nullptr) {
list.head = node;
return pos;
}
else
{
LinkedListNode *pre_node;
for (pre_node = list.head; pre_node->next != nullptr; pre_node = pre_node->next);
node->next = pre_node->next;
pre_node->next = node;
return pos;
}
}
}
void SeparateChainingHashTable::output() {
for (int i = 0; i < capacity; i++) {
SinglelyLinkedList list = data[i];
cout << i << " :";
for (LinkedListNode *node = list.head; node != nullptr; node = node->next) {
cout << node->data << (node->next == nullptr?"":"<-");
}
cout << endl;
}
}