-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathmain.cpp
71 lines (66 loc) · 1.84 KB
/
main.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
63
64
65
66
67
68
69
70
71
class LRUCache : Cache {
public:
LRUCache(int capacity) {
cp = capacity;
head = NULL;
tail = NULL;
}
void set(int key, int value) {
map<int, Node*>::iterator it = mp.find(key);
if (it != mp.end()) {
Node* node = it->second;
node->value = value;
}
else {
if (cp > 0) {
if (mp.size() == cp) {
it = mp.find(tail->key);
if (head == tail) {
head = NULL;
tail = NULL;
}
else {
tail = tail->prev;
tail->next = NULL;
}
delete it->second;
mp.erase(it);
}
Node* node = new Node(key, value);
mp[key] = node;
if (head == NULL && tail == NULL) {
tail = node;
}
else {
head->prev = node;
node->next = head;
}
head = node;
}
}
}
int get(int key) {
map<int, Node*>::iterator it = mp.find(key);
if (it != mp.end()) {
Node* node = it->second;
if (node != head) {
if (node != tail) {
node->next->prev = node->prev;
node->prev->next = node->next;
}
else {
tail = node->prev;
tail->next = NULL;
}
node->next = head;
node->prev = NULL;
head->prev = node;
head = node;
}
return node->value;
}
else {
return -1;
}
}
};