-
Notifications
You must be signed in to change notification settings - Fork 0
/
LRU cache implementation
87 lines (69 loc) · 1.57 KB
/
LRU cache implementation
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
class Node
{
public :
int key ;
int val ;
Node * next ;
Node * prev ;
Node(int k , int v)
{
key = k ;
val = v ;
}
};
class LRUCache {
public:
Node * head = new Node(-1 , -1) ;
Node * tail = new Node(-1,-1) ;
int cap ;
unordered_map <int , Node *> m ;
LRUCache(int capacity) {
head->next = tail ;
tail->prev = head ;
cap = capacity ;
}
Node * addnode(int k , int v)
{
Node * hn = head->next ;
Node * newnode = new Node(k , v) ;
head->next = newnode;
newnode->prev = head ;
hn->prev = newnode ;
newnode->next = hn ;
m[k] = newnode ;
return newnode ;
}
void DELNODE(Node * a)
{
Node * nodeprev = a->prev ;
Node * nodenext = a->next ;
nodeprev->next = nodenext ;
nodenext->prev = nodeprev ;
}
int get(int key) {
if(m.count(key) > 0)
{
int v = m[key]->val ;
DELNODE(m[key]) ;
addnode(key ,v) ;
return m[key]->val ;
}
else
{
return -1 ;
}
}
void put(int key, int value) {
if(m.count(key) > 0)
{
DELNODE(m[key]) ;
m.erase(key) ;
}
if(m.size() == cap)
{
m.erase(tail->prev->key) ;
DELNODE(tail->prev) ;
}
Node * a = addnode(key , value) ;
}
};