-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLRUCache.cpp
68 lines (58 loc) · 1.21 KB
/
LRUCache.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
#include <bits/stdc++.h>
struct Node {
int key, val;
Node *next, *prev;
Node(int k, int v) {
key = k;
val = v;
}
};
class LRUCache
{
Node *head, *tail;
int cap;
public:
unordered_map<int, Node*> mpp;
LRUCache(int capacity)
{
cap = capacity;
head = new Node(0, 0);
tail = new Node(0, 0);
head->next = tail;
tail->prev = head;
}
void insertFront(Node *t) {
t->next = head->next;
t->prev = head;
head->next = t;
t->next->prev = t;
}
void remove(Node *t) {
t->prev->next = t->next;
t->next->prev = t->prev;
t->next = t->prev = NULL;
}
int get(int key)
{
if(mpp.count(key)==0) {
return -1;
}
remove(mpp[key]);
insertFront(mpp[key]);
return mpp[key]->val;
}
void put(int key, int value)
{
if(mpp.count(key)) {
remove(mpp[key]);
}
mpp[key] = new Node(key, value);
insertFront(mpp[key]);
if(mpp.size() > cap) {
mpp.erase(tail->prev->key);
Node *t = tail->prev;
remove(tail->prev);
delete t;
}
}
};