-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache_t.cc
78 lines (69 loc) · 1.83 KB
/
cache_t.cc
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
#include <unordered_map>
template <typename B>
class Node {
public:
B key, val;
Node* next;
Node* prev;
Node(B key, B val) : key(key), val(val), next(nullptr), prev(nullptr){}
};
template <typename A>
class LRUcache {
private:
unordered_map<size_t, Node*> cache;
size_t capacity;
Node* head;
Node* tail;
void removeNode(Node* node) {
Node* P_Node = node->prev;
Node* N_Node = node->next;
P_Node->next = N_Node;
N_Node->prev = P_Node;
}
void insertFront(Node* node) {
node->next = head->next;
node->prev = head;
head->next->prev = node;
head->next = node;
}
void moveFront(Node* node) {
removeNode(node);
insertFront(node);
}
public:
LRUCache();
LRUCache(const LRUCache& cache);
LRUCache(const LRUCache&& cache);
friend std::ostream operator<<(const std::ostream&, LRUCache& cache);
LRUcache(size_t cap): capacity(cap) {
head = new Node(0, 0);
tail = new Node(0, 0);
head->next = tail;
tail->prev = head;
}
int get(size_t key) {
if(cache.find(key) != cache.end()) {
Node* node = cache[key];
moveFront(node);
return node->val;
}
return -1;
}
int put(size_t key, size_t val) {
if(cache.find(key) != cache.end()) {
Node* node = cache[key];
node->val = val;
moveFront(node);
} else {
if(cache.size() == capacity) {
Node* lastNode = tail->prev;
removeNode(lastNode);
cache.erase(lastNode->key);
delete lastNode;
}
Node* newNode = new Node(key, val);
cache[key] = newNode;
insertFront(newNode);
}
}
};