-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhash_table_拉链法.cpp
53 lines (49 loc) · 1.27 KB
/
hash_table_拉链法.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
#include <algorithm>
#include <iostream>
#include <list>
using namespace std;
const int HASH_SIZE = 13;
class HashTable {
private:
list<int> table[HASH_SIZE];
int myhash(int value) const { return value % HASH_SIZE; }
public:
HashTable() {}
void clear() {
for (int i = 0; i < HASH_SIZE; i++) {
table[i].clear();
}
}
bool insert(const int &data) {
int hashValue = myhash(data);
if (find(table[hashValue].begin(), table[hashValue].end(), data) == table[hashValue].end()) {
table[myhash(data)].push_back(data);
return true;
} else {
return false;
}
}
const int operator[](const int data) const { // retrieve
int hashValue = myhash(data);
auto result = find(table[hashValue].begin(), table[hashValue].end(), data);
if (result != table[hashValue].end()) {
return *result;
} else {
return INT_MAX;
}
}
};
int main() {
HashTable test;
test.insert(13);
test.insert(39);
test.insert(25);
test.insert(26);
test.insert(26);
test.insert(26);
cout << test[10] << endl;
cout << test[39] << endl;
cout << test[13] << endl;
cout << test[26] << endl;
system("pause");
}