-
Notifications
You must be signed in to change notification settings - Fork 21
/
LinkedListMap.h
110 lines (93 loc) · 2.35 KB
/
LinkedListMap.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
//
// Created by light on 19-11-8.
//
#ifndef ALG_LINKEDLISTMAP_H
#define ALG_LINKEDLISTMAP_H
template<typename Key, typename Value>
class LinkedListMap : public Map<Key, Value> {
private:
class Node {
public:
Key key;
Value value;
Node *next;
Node(Key key, Value value, Node *next) : key(key), value(value), next(next) {}
Node() {
Key key;
Value value;
new(this)Node(key, value, NULL);
}
friend ostream &operator<<(ostream &out, Node &node) {
out << node.key << ":" << node.value << endl;
return out;
}
};
Node *dummyHead;
int count;
public:
LinkedListMap() {
dummyHead = new Node();
}
~LinkedListMap() {
Node *cur = dummyHead;
while (cur) {
delete cur;
cur = cur->next;
count--;
}
}
virtual int size() {
return count;
}
virtual bool isEmpty() {
return count == 0;
}
virtual Node *getNode(Key key) {
Node *cur = dummyHead->next;
while (cur) {
if (cur->key == key)
return cur;
cur = cur->next;
}
return NULL;
}
virtual bool contain(Key key) {
return getNode(key);
}
virtual Value *search(Key key) {
Node *node = getNode(key);
return (node == NULL) ? NULL : &node->value;
}
virtual void insert(Key key, Value value) {
Node *node = getNode(key);
if (node == NULL) {
dummyHead->next = new Node(key, value, dummyHead->next); // 头插法
count++;
} else {
node->value = value;
}
}
virtual void set(Key key, Value value) {
Node *node = getNode(key);
if (node == NULL)
throw "Key not found ";
node->value = value;
}
virtual Value *remove(Key key) {
Node *prev = dummyHead;
while (prev->next) {
if (prev->next->key == key)
break;
prev = prev->next;
}
if (prev->next) {
Node *delNode = prev->next;
prev->next = delNode->next;
delNode->next = NULL;
count--;
return &delNode->value;
}
return NULL;
}
};
#endif //ALG_LINKEDLISTMAP_H