-
Notifications
You must be signed in to change notification settings - Fork 0
/
hash_class.h
162 lines (156 loc) · 2.26 KB
/
hash_class.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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
struct node
{
String key;
String value;
node* next;
};
class hash_table
{
private:
node** tbl;
int nItems;
int ar_size;
int hash_func(String key);
bool isprim(int x);
protected:
public:
void insert(String key, String value);
void remove(String key );
String find(String key);
hash_table(int nItems);
~hash_table();
};
bool hash_table::isprim(int x)
{
for (int l = x - 1; l >= 2; l--)
{
if (x % l == 0)
{
return false;
}
}
return true;
}
hash_table::hash_table(int _nItems)
{
tbl = NULL;
nItems =_nItems;
int startsiz = 0;
startsiz = _nItems * 100 / 70;
while (isprim(startsiz) != true) { startsiz++; }
ar_size = startsiz;
tbl = new node * [ar_size];
for (int i = 0; i < ar_size; i++)
{
tbl[i] = NULL;
}
}
hash_table::~hash_table()
{
for (int i = 0; i < ar_size; i++)
{
node* p = tbl[i];
node* pp = p;
while (p != NULL)
{
p = p->next;
delete pp;
pp = p;
}
}
delete tbl;
}
int hash_table::hash_func(String key)
{
int hash = 0;
for (int i = 1; i <= key.Length(); i++)
{
char ch = (key[i] - 0);
hash = (hash * 256 + ch) % ar_size;
}
return hash;
}
String hash_table::find(String key)
{
int idx = hash_func(key);
node* _ptn = tbl[idx];
String res="";
while (_ptn != NULL)
{
if (_ptn->key == key)
{
res = _ptn->value;
break;
}
else
{
_ptn = _ptn->next;
}
}
return res;
}
void hash_table::insert(String key, String value)
{
node* _tn = new node;
_tn->key = key;
_tn->value = value;
_tn->next = NULL;
int idx = hash_func(key);
if ( tbl[idx] == NULL)
{
tbl[idx] = _tn;
}
else
{
bool is_new = true;
node* _ptn = tbl[idx];
while (_ptn->next != NULL)
{
if (_ptn->key == key)
{
_ptn->value = value;
is_new = false;
break;
}
else
{
_ptn = _ptn->next;
}
}
if (_ptn->next == NULL)
{
if (_ptn->key == key)
{
_ptn->value = value;
is_new = false;
}
}
if (is_new == true)
{
_ptn->next = _tn;
}
}
}
void hash_table::remove(String key)
{
int idx = hash_func(key);
if (tbl[idx]->key == key)
{
tbl[idx] = tbl[idx]->next;
}
else
{
node* _tn = tbl[idx];
node* _ptn = _tn;
while (_tn->key != key && _tn != NULL)
{
_ptn = _tn;
_tn = _tn->next;
}
if (_tn->key == key)
{
_ptn->next = _tn->next;
delete _tn;
}
}
}