-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlru.cpp
109 lines (85 loc) · 1.83 KB
/
lru.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include<iostream>
#include<list>
#include<unordered_map>
using namespace std;
//Node to store the data (Linked List)
class Node{
public:
string key;
int value;
Node(string key,int value){
this->key = key;
this->value = value;
}
};
//LRU Cache Data Structure
class LRUCache{
public:
int maxSize;
list<Node> l;
unordered_map<string,list<Node>::iterator > m;
LRUCache(int maxSize){
this->maxSize = maxSize > 1 ? maxSize : 1;
}
void insertKeyValue(string key,int value){
//2 cases
if(m.count(key)!=0){
//replace the old value and update
auto it = m[key];
it-> value = value;
}
else{
//check if cache if full or not
//remove the least recently used item from cache
if(l.size()==maxSize){
Node last = l.back();
m.erase(last.key); //remove from hashmap
l.pop_back(); //remove from linked list
}
Node n(key,value);
l.push_front(n);
m[key] = l.begin();
}
}
int* getValue(string key){
if(m.count(key)!=0){
auto it = m[key];
int value = it->value;
l.push_front(*it);
l.erase(it);
m[key] = l.begin();
return &l.begin()->value;
}
return NULL;
}
string mostRecentKey(){
return l.front().key;
}
};
int main(){
LRUCache lru(3);
lru.insertKeyValue("mango",10);
lru.insertKeyValue("apple",20);
lru.insertKeyValue("guava",30);
cout << lru.mostRecentKey() <<endl;
lru.insertKeyValue("mango",40);
cout << lru.mostRecentKey() <<endl;
int *orders = lru.getValue("mango");
if(orders!=NULL){
cout<<"Order of Mango "<<*orders <<endl;
}
lru.insertKeyValue("banana",20);
if(lru.getValue("apple")==NULL){
cout<<"apple doesn't exist";
}
if(lru.getValue("guava")==NULL){
cout<<"guava doesn't exist";
}
if(lru.getValue("banana")==NULL){
cout<<"banana doesn't exist";
}
if(lru.getValue("mango")==NULL){
cout<<"mango doesn't exist";
}
return 0;
}