-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlru-cache.cpp
88 lines (76 loc) · 2.06 KB
/
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
struct Listnode {
int key, val;
Listnode *next, *prev;
Listnode(int _key, int _val) {
key = _key;
val = _val;
next = NULL;
prev = NULL;
}
};
class LRUCache {
private:
int totalCapacity, currCapacity;
unordered_map<int, Listnode*> mp;
Listnode *front, *tail;
public:
LRUCache(int capacity) {
totalCapacity = capacity;
currCapacity = 0;
mp.clear();
front = new Listnode(0, 0);
tail = new Listnode(0, 0);
front -> next = tail;
tail -> prev = front;
}
int get(int key) {
if(mp.count(key)) {
Listnode *temp = mp[key];
int ans = temp->val;
deleteNode(temp);
mp.erase(key);
currCapacity--;
put(key, ans);
return ans;
}
return -1;
}
void put(int key, int value) {
if(mp.count(key)) {
deleteNode(mp[key]);
mp.erase(key);
currCapacity--;
put(key, value);
}
else if(currCapacity < totalCapacity) {
currCapacity++;
Listnode *node = new Listnode(key, value);
Listnode *nextNode = front->next;
front -> next = node;
node -> prev = front;
nextNode -> prev = node;
node -> next = nextNode;
mp[key] = node;
}
else {
Listnode *lastNode = tail -> prev;
mp.erase(lastNode->key);
deleteNode(lastNode);
currCapacity--;
put(key, value);
}
}
void deleteNode(Listnode *ptr) {
Listnode *prevNode = ptr -> prev;
Listnode *nextNode = ptr -> next;
prevNode -> next = nextNode;
nextNode -> prev = prevNode;
}
};
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache* obj = new LRUCache(capacity);
* int param_1 = obj->get(key);
* obj->put(key,value);
*/
// DLL + unorderd_map