-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlrucache.cpp
More file actions
95 lines (93 loc) · 2.21 KB
/
lrucache.cpp
File metadata and controls
95 lines (93 loc) · 2.21 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
typedef struct node{
int key;
int val;
struct node* next;
struct node* prev;
}node_t;
class LRUCache{
public:
int size;
int count;
node_t* head;
node_t *tail;
map<int, node_t*>mm;
LRUCache(int capacity) {
size = capacity;
count = 0;
head = new node_t;
tail = new node_t;
head->next = tail;
tail->prev = head;
mm.clear();
}
int get(int key) {
if (mm.count(key) == 0)
{
return -1;
}
auto ll = mm[key];
auto pp = ll->prev;
auto nn = ll->next;
pp->next = nn;
nn->prev = pp;
auto hh = head->next;
head->next = ll;
ll->next = hh;
hh->prev = ll;
ll->prev = head;
return ll->val;
}
void set(int key, int value) {
if (mm.count(key) != 0)
{
auto ll = mm[key];
ll->val = value;
auto pp = ll->prev;
auto nn = ll->next;
pp->next = nn;
nn->prev = pp;
auto hh = head->next;
head->next = ll;
ll->next = hh;
hh->prev = ll;
ll->prev = head;
return;
}
if (count != size)
{
count++;
node_t *nn = new node_t;
nn->key = key;
nn->val = value;
auto hh = head->next;
head->next = nn;
nn->next = hh;
hh->prev = nn;
nn->prev = head;
mm[key] = nn;
return;
}
else
{
auto ll = tail->prev;
auto np = ll->prev;
np->next = tail;
tail->prev = np;
auto nk = ll->key;
auto pos = mm.find(nk);
if (pos != mm.end())
{
mm.erase(pos);
}
ll->key = key;
ll->val = value;
mm[key] = ll;
auto hh = head->next;
head->next = ll;
ll->next = hh;
hh->prev = ll;
ll->prev = head;
return;
}
}
};