-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlru_cache.hpp
116 lines (105 loc) · 2.05 KB
/
lru_cache.hpp
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
#ifndef lru_cache
#define lru_cache
#include<iostream>
#include<string>
#include<unordered_map>
using namespace std;
class ListNode {
public:
string key;
string value;
ListNode *prev;
ListNode *next;
ListNode():key(""),value(""),prev(NULL),next(NULL){}
ListNode(string key, string value):key(key),value(value),prev(NULL),next(NULL) {}
};
class lrucache {
private:
unordered_map<string,ListNode*> memo;
ListNode* head=new ListNode;
ListNode* tail=new ListNode;
int capacity;
void pushToHead(ListNode* node)
{
node->next=head->next;
head->next->prev=node;
node->prev=head;
head->next=node;
}
void moveToHead(ListNode* node)
{
node->prev->next=node->next;
node->next->prev=node->prev;
pushToHead(node);
}
void delTail(ListNode* node)
{
node->prev->next=tail;
tail->prev=node->prev;
}
public:
lrucache(int capacity):capacity(capacity) {
head->next=tail;
tail->prev=head;
}
~lrucache() {
for(auto& i:memo) {
delete i.second;
}
}
void display()
{
ListNode *cur=head->next;
while(cur->next!=NULL)
{
cout<<"key: "<<cur->key<<" value: "<<cur->value<<endl;
cur=cur->next;
}
}
void put_in_cache(string key,string value)
{
if(memo.count(key))
{
memo[key]->value=value;
moveToHead(memo[key]);
}
else
{
ListNode* node=new ListNode(key,value);
pushToHead(node);
memo[key]=node;
if(memo.size()>capacity)
{
ListNode* temp=tail->prev;
delTail(temp);
memo.erase(temp->key);
delete temp;
}
}
}
string get_from_cache(string key)
{
if(memo.count(key))
{
moveToHead(memo[key]);
return memo[key]->value;
}
else
{
return "";
}
}
void delete_from_cache(string key)
{
if(memo.count(key))
{
ListNode* del=memo[key];
del->prev->next=del->next;
del->next->prev=del->prev;
memo.erase(key);
delete del;
}
}
};
lrucache cache(3);
#endif