-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashMap.hpp
More file actions
115 lines (99 loc) · 2.7 KB
/
HashMap.hpp
File metadata and controls
115 lines (99 loc) · 2.7 KB
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
#ifndef TRAIN_TICKET_HASHMAP_HPP
#define TRAIN_TICKET_HASHMAP_HPP
#include <functional>
template <class Key,class Data,class Hash = std::hash<Key>>
class HashMap{
private:
class LinkList{
private:
struct Node{
Node * next;
Key key;
Data data;
Node() = delete;
Node(Node * _next,const Key & _key,const Data & _data):next(_next),key(_key),data(_data){}
};
int dataSize;
Node *head;
public:
LinkList():dataSize(0),head(nullptr){}
~LinkList(){
while(head != nullptr){
Node * tmp = head;
head = head->next;
delete tmp;
}
}
void insert(const Key & _key,const Data & _data){
head = new Node(head,_key,_data);
++dataSize;
}
Node * find(const Key & _key){
if(dataSize == 0) return nullptr;
Node * q = head;
while(q != nullptr){
if(q->key == _key) return q;
q = q->next;
}
return nullptr;
}
void erase(const Key & _key){
if(dataSize == 0) return;
if(head->key == _key){
Node * tmp = head;
head = head->next;
delete tmp;
--dataSize;
return;
}
Node * p = nullptr; Node * q = head;
while(q != nullptr){
if(q->key == _key) break;
p = q; q = q->next;
}
p->next = q->next;
delete q;
--dataSize;
}
};
int capacity;
LinkList * dataSet;
Hash hash;
int getIndex(const Key & _key){
return hash(_key) % capacity;
}
public:
HashMap() = delete;
explicit HashMap(int _capacity):capacity(_capacity){
dataSet = new LinkList[_capacity];
}
~HashMap(){
delete [] dataSet;
}
bool exist(const Key & _key){
int index = getIndex(_key);
return (dataSet[index].find(_key) != nullptr);
}
// 不可重复添加相同key
void insert(const Key & _key,const Data & _data){
int index = getIndex(_key);
dataSet[index].insert(_key,_data);
}
void erase(const Key & _key){
int index = getIndex(_key);
dataSet[index].erase(_key);
}
// 保证有此key
Data & find(const Key & _key){
int index = getIndex(_key);
return dataSet[index].find(_key)->data;
}
Data & operator [](const Key & _key){
return this->find(_key);
}
void clear(){
delete [] dataSet;
dataSet = new LinkList[capacity];
}
};
#endif