-
Notifications
You must be signed in to change notification settings - Fork 138
/
Solution.cpp
62 lines (62 loc) · 1.3 KB
/
Solution.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
54
55
56
57
58
59
60
61
62
class LRUCache: Cache {
public:
LRUCache(int l) {
cp = l;
tail = NULL;
head = NULL;
mp = {};
}
virtual void set(int k, int v) {
auto it = mp.find(k);
if (it == mp.end()) {
Node *node = new Node(k, v);
if (cp == 0) {
node->next = head;
head->prev = node;
head = node;
Node *tmp = tail;
mp.erase(tmp->key);
tail = tail->prev;
delete tmp;
} else {
cp--;
if (head == NULL) {
head = node;
tail = node;
} else {
node->next = head;
head->prev = node;
head = node;
}
}
mp[k] = node;
} else {
Node *tmp = it->second;
if (tmp != head) {
if (tmp == tail) {
tail = tmp->prev;
tmp->prev->next = NULL;
tmp->prev = NULL;
tmp->next = head;
head->prev = tmp;
head = tmp;
} else {
tmp->prev->next = tmp->next;
tmp->next->prev = tmp->prev;
tmp->prev = NULL;
tmp->next = head;
head->prev = tmp;
head = tmp;
}
}
head->value = v;
}
}
virtual int get(int k) {
auto it = mp.find(k);
if (it != mp.end()) {
return it->second->value;
}
return -1;
}
};