-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path146.lru-cache.161880653.ac.cpp
88 lines (80 loc) · 1.9 KB
/
146.lru-cache.161880653.ac.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
class LRUCache {
public:
struct dllnode
{
int key;
int value;
dllnode * pre;
dllnode * post;
};
int cap;
int count=0;
dllnode * head ;
dllnode * tail;
map<int,dllnode*> mp;
LRUCache(int capacity) {
cap=capacity;
head = new dllnode;
tail = new dllnode;
head->pre = NULL;
head->post = tail;
tail->pre = head;
tail->post = NULL;
}
void addnode(dllnode * node)
{
node->pre = head;
node->post = head->post;
head->post->pre = node;
head->post=node;
}
dllnode * remove(dllnode * node)
{
dllnode * prev = node->pre;
dllnode* next = node->post;
prev->post = next;
next->pre = prev;
return node;
}
int get(int key) {
if(mp.find(key)!=mp.end())
{
dllnode * x=remove(mp[key]);
addnode(x);
return mp[key]->value;
}
else return -1;
}
void put(int key, int value) {
if(mp.find(key)==mp.end())
{
mp[key]= new dllnode;
mp[key]->value= value;
mp[key]->key = key;
addnode(mp[key]);
count++;
cout<<"hhhh"<<key<<" ";
if(count>cap)
{
cout<<"lll"<<count<<" "<<cap;
count--;
dllnode* x =remove(tail->pre);
cout<<x->key<<" ";
mp.erase(x->key);
}
}
else
{
cout<<"hereee";
mp[key]->value= value;
dllnode * x = remove(mp[key]);
addnode(x);
}
}
};
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache obj = new LRUCache(capacity);
* int param_1 = obj.get(key);
* obj.put(key,value);
*/