forked from Raju1822/HacktoberFest_2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLRU
124 lines (106 loc) · 2.38 KB
/
LRU
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int key;
int value;
Node *pre;
Node *next;
Node(int k, int v)
{
key = k;
value = v;
pre=NULL;next=NULL;
}
};
class LRUCache {
public:
unordered_map<int, Node*> map;
int capacity, count;
Node *head, *tail;
LRUCache(int c)
{
capacity = c;
head = new Node(0, 0);
tail = new Node(0, 0);
head->next = tail;
tail->pre = head;
head->pre = NULL;
tail->next = NULL;
count = 0;
}
void deleteNode(Node *node)
{
node->pre->next = node->next;
node->next->pre = node->pre;
}
void addToHead(Node *node)
{
node->next = head->next;
node->next->pre = node;
node->pre = head;
head->next = node;
}
int get(int key)
{
if (map[key] != NULL) {
Node *node = map[key];
int result = node->value;
deleteNode(node);
addToHead(node);
cout<<"Got the value : " <<
result << " for the key: " << key<<endl;
return result;
}
cout<<"Did not get any value" <<
" for the key: " << key<<endl;
return -1;
}
void set(int key, int value)
{
cout<<"Going to set the (key, "<<
"value) : (" << key << ", " << value << ")"<<endl;
if (map[key] != NULL) {
Node *node = map[key];
node->value = value;
deleteNode(node);
addToHead(node);
}
else {
Node *node = new Node(key, value);
map[key]= node;
if (count < capacity) {
count++;
addToHead(node);
}
else {
map.erase(tail->pre->key);
deleteNode(tail->pre);
addToHead(node);
}
}
}
};
int main(){
{
LRUCache cache(2);
// it will store a key (1) with value
// 10 in the cache.
cache.set(1, 10);
// it will store a key (2) with value 20 in the cache.
cache.set(2, 20);
cout<<"Value for the key: 1 is " << cache.get(1)<<endl; // returns 10
// removing key 2 and store a key (3) with value 30 in the cache.
cache.set(3, 30);
cout<<"Value for the key: 2 is " <<
cache.get(2)<<endl; // returns -1 (not found)
// removing key 1 and store a key (4) with value 40 in the cache.
cache.set(4, 40);
cout<<"Value for the key: 1 is " <<
cache.get(1)<<endl; // returns -1 (not found)
cout<<"Value for the key: 3 is " <<
cache.get(3)<<endl; // returns 30
cout<<"Value for the key: 4 is " <<
cache.get(4)<<endl; // return 40
return 0;
}