1+ #include < algorithm>
2+ #define bucket_num 1543
3+ using namespace std ;
4+
5+ // 哈希函数为取余法,因此只适用于整形
6+ template <class Value >
7+ class hash_table
8+ {
9+ // 冲突以开链法解决,STL和JDK都是以这种方法实现
10+ struct node
11+ {
12+ node* next;
13+ Value value;
14+ node (Value val = 0 ): next(nullptr ), value(val) {}
15+ };
16+ private:
17+ node* buckets;
18+ public:
19+ // 桶的大小通常根据需求选择某个质数
20+ hash_table (): buckets(new node[bucket_num]) {};
21+ ~hash_table ()
22+ {
23+ destroy (buckets);
24+ delete[] buckets;
25+ }
26+
27+ // 可以有重复值
28+ // void insert(const Value value)
29+ // {
30+ // int hashcode = value % bucket_num;
31+ // node* head = &buckets[hashcode];
32+ // while (head->next != nullptr) head = head->next;
33+ // head->next = new node(value);
34+ // }
35+
36+ // 不能有重复值
37+ bool insert (const Value value)
38+ {
39+ int hashcode = value % bucket_num;
40+ node* head = &buckets[hashcode];
41+ while (head->next != nullptr && head->next ->value != value) head = head->next ;
42+ if (head->next == nullptr )
43+ head->next = new node (value);
44+ else
45+ return false ;
46+ return true ;
47+ }
48+
49+ bool remove (const Value value)
50+ {
51+ int hashcode = value % bucket_num;
52+ node* head = &buckets[hashcode];
53+ while (head->next != nullptr && head->next ->value != value) head = head->next ;
54+ if (head->next == nullptr ) return false ;
55+ else
56+ {
57+ node* temp = head->next ;
58+ head->next = head->next ->next ;
59+ delete temp;
60+ }
61+ return true ;
62+ }
63+
64+ bool find (const Value value)
65+ {
66+ int hashcode = value % bucket_num;
67+ node* head = &buckets[hashcode];
68+ while (head->next != nullptr && head->next ->value != value) head = head->next ;
69+ if (head->next == nullptr ) return false ;
70+ else return true ;
71+ }
72+
73+ private:
74+ void destroy (node* buckets)
75+ {
76+ for (int i = 0 ; i < bucket_num; ++i)
77+ {
78+ node* head = &buckets[i];
79+ head = head->next ;
80+ while (head != nullptr )
81+ {
82+ node* temp = head;
83+ head = head->next ;
84+ delete temp;
85+ }
86+ }
87+ }
88+ };
0 commit comments