-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlru_cache.cpp
More file actions
132 lines (107 loc) · 2.34 KB
/
lru_cache.cpp
File metadata and controls
132 lines (107 loc) · 2.34 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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#include "lru_cache.h"
LRUCache::LRUCache(std::size_t capacity)
: cap(capacity), head(nullptr), tail(nullptr) {}
LRUCache::~LRUCache() {
free_all();
}
void LRUCache::add_front(Node* node) {
node->prev = nullptr;
node->next = head;
if (head != nullptr) {
head->prev = node;
} else {
tail = node;
}
head = node;
}
void LRUCache::detach(Node* node) {
if (node->prev != nullptr) {
node->prev->next = node->next;
} else {
head = node->next;
}
if (node->next != nullptr) {
node->next->prev = node->prev;
} else {
tail = node->prev;
}
node->prev = nullptr;
node->next = nullptr;
}
void LRUCache::touch(Node* node) {
if (node == head) {
return;
}
// 被访问过的节点移动到头部,头部始终代表最近使用。
detach(node);
add_front(node);
}
LRUCache::Node* LRUCache::pop_tail() {
Node* old = tail;
if (old != nullptr) {
detach(old);
}
return old;
}
void LRUCache::free_all() {
Node* cur = head;
while (cur != nullptr) {
Node* next = cur->next;
delete cur;
cur = next;
}
head = nullptr;
tail = nullptr;
cache.clear();
}
int LRUCache::get(int key) {
auto it = cache.find(key);
if (it == cache.end()) {
return -1;
}
Node* node = it->second;
touch(node);
return node->value;
}
void LRUCache::put(int key, int value) {
if (cap == 0) {
return;
}
auto it = cache.find(key);
if (it != cache.end()) {
Node* node = it->second;
node->value = value;
touch(node);
return;
}
Node* node = new Node(key, value);
add_front(node);
cache[key] = node;
if (cache.size() > cap) {
Node* old = pop_tail();
cache.erase(old->key);
delete old;
}
}
std::size_t LRUCache::size() const {
return cache.size();
}
std::size_t LRUCache::capacity() const {
return cap;
}
bool LRUCache::empty() const {
return cache.empty();
}
bool LRUCache::contains(int key) const {
return cache.find(key) != cache.end();
}
std::vector<int> LRUCache::keys() const {
std::vector<int> out;
out.reserve(cache.size());
Node* cur = head;
while (cur != nullptr) {
out.push_back(cur->key);
cur = cur->next;
}
return out;
}