-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlru_cache.cpp
59 lines (55 loc) · 1.39 KB
/
lru_cache.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
class Node() {
Node* front;
Node* back;
int val;
Node(): front(NULL), back(NULL), val(-1) {};
Node(int x): front(NULL), back(NULL), val(x) {};
};
class LRUCache() {
private:
int maxCapacity;
int capactiy;
Node* head;
Node* tail;
unordered_map<int, Node*> hash;
public:
LRUCache(int c): maxCapacity(c), capactiy(0), head(NULL), tail(NULL) {};
int get(int key) {
if (hash.find(key)==hash.end()) {
return -1;
}
Node* temp = hash[key];
if (temp == head) {
return temp->val;
}
temp->prev->next = temp->next;
temp->next->prev = temp->prev;
temp->next = head;
head->prev = temp;
head = temp;
head->prev = NULL;
return temp->val;
}
void put(int value) {
Node* temp = new Node(value);
if (capactiy < maxCapacity) {
if (head == NULL) {
head = tail = temp;
hash[value] = temp;
} else {
tail->next = temp;
temp->prev = tail;
tail = tail->next;
}
capactiy++;
} else {
hash.erase(head->value);
head = head->next;
head->prev = NULL;
tail->next = temp;
temp->prev = tail;
tail = temp;
}
hash[value] = temp;
}
};