-
Notifications
You must be signed in to change notification settings - Fork 0
/
hashTableLinear.cpp
92 lines (83 loc) · 1.6 KB
/
hashTableLinear.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
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
#include "hashTableLinear.h"
void HashTableLinear::resize(size_t newCapacity) {
int* oldTable = table;
int oldCapacity = capacity;
size = 0;
capacity = newCapacity;
table = new int[capacity];
for (size_t i = 0; i < capacity; i++) {
table[i] = -1;
}
for (size_t i = 0; i < oldCapacity; i++) {
if (oldTable[i] != -1) {
insert(i, oldTable[i]);
}
}
delete[] oldTable;
}
HashTableLinear::HashTableLinear(size_t capacity)
{
this->capacity = capacity;
table = new int[capacity];
for (size_t i = 0; i < capacity; i++) {
table[i] = -1;
}
size = 0;
}
HashTableLinear::~HashTableLinear()
{
delete[] table;
size = 0;
capacity = 0;
}
int HashTableLinear::hash(int key)
{
return key % capacity;
}
void HashTableLinear::insert(int key, int value)
{
int index = hash(key);
while (table[index] != -1) {
index = (index + 1) % capacity;
}
table[index] = value;
size++;
if (size >= capacity) {
resize(capacity * 2);
}
}
int HashTableLinear::remove(int key) {
int index = hash(key);
while (table[index] != -1) {
if (index == key) {
int value = table[index];
table[index] = -1;
size--;
return value;
}
index = (index + 1) % capacity;
}
if (size == capacity / 4)
resize(capacity / 2);
}
void HashTableLinear::display()
{
for (size_t i = 0; i < capacity; i++) {
cout << i << ": ";
if (table[i] != -1)
cout << table[i];
cout << endl;
}
cout << endl;
}
int HashTableLinear::search(int key) {
int index = hash(key);
int startIndex = index;
do {
if (index == key) {
return table[index];
}
index = (index + 1) % capacity;
} while (index != startIndex);
return -1;
}