-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLRUCache.cpp
More file actions
106 lines (83 loc) · 2.51 KB
/
LRUCache.cpp
File metadata and controls
106 lines (83 loc) · 2.51 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
96
97
98
99
100
101
102
103
104
105
106
#include<iostream>
#include<mutex>
#include<thread>
using namespace std;
mutex g_cout_mutex;
class CacheNode{
public:
int val;
int key;
CacheNode* next;
CacheNode* prev;
CacheNode(int key, int val){
this->key = key;
this->val = val;
next = nullptr;
prev = nullptr;
}
void changeValue(int value){
this->val = value;
}
};
class LRUCache {
unordered_map<int, CacheNode*> nodeAddress;
CacheNode* leastRecentNode;
CacheNode* mostRecentNode;
int capacity;
void makeNodeLatest(CacheNode* node){
if(leastRecentNode==mostRecentNode) return;
if(node == leastRecentNode) leastRecentNode = leastRecentNode->next;
if(node == mostRecentNode) return;
CacheNode* nextNode = node->next;
CacheNode* prevNode = node->prev;
if(prevNode)prevNode->next = nextNode;
nextNode->prev = prevNode;
mostRecentNode->next = node;
node->prev = mostRecentNode;
node->next = nullptr;
mostRecentNode=mostRecentNode->next;
return;
}
void deleteHeadAsCapacityExceeded(){
CacheNode* currNode = leastRecentNode;
leastRecentNode = leastRecentNode->next;
leastRecentNode->prev = nullptr;
nodeAddress.erase(currNode->key);
delete currNode;
}
public:
LRUCache(int capacity) {
this->capacity = capacity;
leastRecentNode = nullptr;
mostRecentNode = nullptr;
}
int get(int key) {
if(nodeAddress.size()==0) return -1;
if(nodeAddress.find(key)!=nodeAddress.end()){
makeNodeLatest(nodeAddress[key]);
return nodeAddress[key]->val;
}
return -1;
}
void put(int key, int value) {
if(nodeAddress.find(key)!=nodeAddress.end()){
nodeAddress[key]->changeValue(value);
makeNodeLatest(nodeAddress[key]);
return;
} //update
CacheNode* newNode = new CacheNode(key,value); //add
nodeAddress[key] = newNode;
if(!leastRecentNode) { //no node till now
leastRecentNode = newNode;
mostRecentNode = newNode;
return;
}
mostRecentNode->next = newNode;
newNode->prev = mostRecentNode;
mostRecentNode = mostRecentNode->next;
if(nodeAddress.size()>capacity) deleteHeadAsCapacityExceeded();
return;
}
};
int main(){
}