-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleast-recently-used-cache.cpp
More file actions
114 lines (89 loc) · 2.19 KB
/
least-recently-used-cache.cpp
File metadata and controls
114 lines (89 loc) · 2.19 KB
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
#include <bits/stdc++.h>
using namespace std;
class LRUCache {
class Node {
public:
int val;
int key;
Node* next;
Node* prev;
Node(int key, int val) {
this->val = val;
this->key = key;
this->next = nullptr;
this->prev = nullptr;
}
};
public:
int capacity;
int remaining;
unordered_map<int, Node*> map;
Node* head;
Node* tail;
LRUCache(int capacity) {
this->capacity = capacity;
this->remaining = capacity;
this->head = new Node(-1, -1);
this->tail = new Node(-1, -1);
this->head->next = this->tail;
this->tail->prev = this->head;
}
int get(int key) {
if(map.find(key) == map.end()) {
return -1;
}
Node* c = map[key];
Node *p = c->prev;
Node *n = c->next;
p->next = n;
n->prev = p;
c->next = nullptr;
c->prev = nullptr;
Node* head_next = this->head->next;
c->next = head_next;
c->prev = this->head;
head_next->prev = c;
this->head->next = c;
return c->val;
}
void put(int key, int val) {
if(this->map.find(key) != this->map.end()) {
Node *c = map[key];
Node *p = c->prev;
Node *n = c->next;
p->next = n;
n->prev = p;
this->map.erase(c->key);
delete c;
this->remaining++;
}
if(this->remaining == 0) {
Node *n = this->tail->prev;
Node *t = n->prev;
t->next = this->tail;
this->tail->prev=t;
this->map.erase(n->key);
delete n;
this->remaining++;
}
Node *n = new Node(key, val);
Node* t = this->head->next;
n->next = t;
n->prev = this->head;
this->head->next = n;
t->prev = n;
this->map[key] = n;
this->remaining--;
}
};
int main() {
LRUCache* l = new LRUCache(2);
cout << l->get(2) << endl;
l->put(2, 6);
cout << l->get(1) << endl;
l->put(1, 5);
l->put(1, 2);
cout << l->get(1) << endl;
cout << l->get(2) << endl;
return 0;
}