-
Notifications
You must be signed in to change notification settings - Fork 0
/
146. LRU Cache.cpp
98 lines (93 loc) · 1.62 KB
/
146. LRU Cache.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
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
#include<unordered_map>
#include<stdlib.h>
#include<utility>
using namespace std;
class LRUlist {
public:
int key;
LRUlist *next;
LRUlist *pre;
LRUlist(int k) :key(k), next(NULL), pre(NULL) {}
};
class LRUCache {
private:
unordered_map<int, int>cache;
LRUlist *head;
LRUlist *rear;
int size = 0;
public:
LRUCache(int capacity) {
size = capacity;
head = new LRUlist(0);
rear = head;
}
int get(int key) {
auto a = cache.find(key);
if (a != cache.end()) {
return a->second;
}
else return -1;
}
void set(int key, int value) {
auto a = cache.find(key);
if (a != cache.end()) {
Listkeynode_delete(key);
List_insert(key);
a->second = value;
}
else {
Add(key, value);
}
}
private:
void List_insert(int key) {
LRUlist *p = new LRUlist(key);
rear->next = p;
p->pre = rear;
rear = p;
}
int Listheadnode_delete() {
LRUlist *p = head->next;
if (p == rear) {
rear = head;
head->next = NULL;
}
else {
head->next = p->next;
p->next->pre = head;
}
int key = p->key;
free(p);
return key;
}
void Listkeynode_delete(int key) {
LRUlist *p = head;
while (p->key != key) p = p->next;
if (p == rear) {
p->pre->next = NULL;
}
else {
p->pre->next = p->next;
p->next->pre = p->pre;
}
free(p);
}
void Add(int key, int value) {
if (cache.size() == size) {
int key = Listheadnode_delete();
cache.erase(key);
}
cache[key] = value;
List_insert(key);
}
};
int main(int argc, char*argv[]) {
LRUCache *test = new LRUCache(2);
test->set(2, 1);
test->set(2, 2);
test->get(2);
test->set(1, 1);
test->set(4, 1);
test->get(2);
system("pause");
}