-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLRU-CacheDesign
148 lines (125 loc) · 3.13 KB
/
LRU-CacheDesign
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
#include <iostream>
using namespace std;
class Node {
int key;
int value;
Node* next;
Node* prev;
Node(int k, int v){
key =k;
value = v;
next = NULL;
prev= NULL;
}
}
class DoublyLinkedList {
Node* front;
Node* rear;
int size;
int capacity;
DoublyLinkedList(int cap){
front = NULL;
rear = NULL;
capacity = cap;
}
bool isDllFull() {
return size == capacity;
}
void move2head(Node* N){
if ((N == front) && (N ==NULL))
return;
else {
if (N == rear) {
rear->prev->next = rear->next;
rear = rear->prev;
}
else{
N->prev->next = N->next;
N->next->prev= N->prev;
}
N->prev = NULL;
N->next = front;
font->prev = N;
front = N;
}
}
void insertAtHead(Node* N) {
if (front== NULL && rear == NULL ){
front = N;
rear = N;
}
else if (N == front){
return;
}
else {
N->next = front;
front->prev = N;
front = N;
size++;
}
}
Node* getRear(){
if (!rear) return NULL;
else
return rear;
}
void removeDllTail(){
Node* temp ;
if (!rear) return;
if (rear != front) {
rear->prev->next = rear->next;
temp = rear;
rear = rear->prev;
delete temp;
}
else{
delete rear;
rear= NULL;
front = NULL;
}
size--;
}
}
class LRUcache {
DoublyLinkedList *dll = new DoublyLinkedList();
unordered_map<int, Node*> umap;
int get(int key){
unordered_map<int, Node*>:: iterator got = umap.find(key);
if (got != umap.end()){
dll->move2head(got->second);
return got->first;
}
else{
return -1;
}
}
}
void put(int key, int value){
unordered_map<int, Node*>:: iterator got = umap.find(key);
if (got != umap.end()){
got->second->value = value;
dll->move2head(got->second);
}
else{
// the value does not exist in the cache. so we have to add it to the hash map and dll
// but if the dll is full we must first evict one node from the dll. and also replace that
// in the hashtable
if (dll->isDllFull()) {
Node* tail = dll->getDllTail();
if (!tail){
got->first = tail->key;
dll->removeDllTail();
umap.erase(got->first);
}
}
Node newnode = new Node(key, value);
umap[key] = newnode;
dll->insertAtHead(umap[key]);
}
}
}
int main()
{
cout<<"Hello World";
return 0;
}