-
Notifications
You must be signed in to change notification settings - Fork 0
/
092_LRUCacheImplementation.cpp
90 lines (72 loc) · 1.42 KB
/
092_LRUCacheImplementation.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
#include<bits/stdc++.h>
using namespace std;
class Node{
public:
int key, data;
Node *prev;
Node *next;
Node(int _key, int _data){
// cout<<_key<<" ->"<<_data<<endl;
data=_data;
key=_key;
next=NULL;
prev=NULL;
}
};
class LRUCache
{
public:
int capacity;
Node *head=new Node(0, 0);
Node *tail=new Node(0, 0);
map<int, Node*> hashMap;
LRUCache(int capacity)
{
// Write your code here
this->capacity=capacity;
head->next=tail;
tail->prev=head;
}
void createNode(Node *node){
Node *temp=head->next;
node->next=temp;
node->prev=head;
temp->prev=node;
head->next=node;
}
void deleteNode(Node* node){
node->next->prev=node->prev;
node->prev->next=node->next;
}
int get(int key)
{
// Write your code here
if(hashMap.find(key) != hashMap.end()){
Node* node=hashMap[key];
int value=node->data;
deleteNode(node);
hashMap.erase(key);
createNode(node);
hashMap[key]=node;
return value;
}
return -1;
}
void put(int key, int value)
{
// Write your code here
if(hashMap.find(key) != hashMap.end()){
Node* node=hashMap[key];
deleteNode(node);
hashMap.erase(key);
}
if(hashMap.size()==capacity){
Node* node=tail->prev;
deleteNode(node);
hashMap.erase(node->key);
}
Node *node=new Node(key, value);
createNode(node);
hashMap[key]=head->next;
}
};