forked from algoristyAlternate/code_for_fun
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlru_cache.cpp
More file actions
102 lines (84 loc) · 2.06 KB
/
lru_cache.cpp
File metadata and controls
102 lines (84 loc) · 2.06 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
class Node {
public:
int val,key;
Node *left,*right;
Node(int key, int val){
this->val = val;
this->key = key;
this->left = NULL;
this->right = NULL;
}
};
class LRUCache {
public:
Node *head, *tail;
int capacity,size;
unordered_map<int,Node *> key_address;
LRUCache(int capacity) {
this->capacity = capacity;
this->size = 0;
this->head = NULL;
this->tail = NULL;
}
void delete_node(Node *p){
if(p->left!=NULL){
p->left->right = p->right;
}
else{
head = p->right;
}
if(p->right!=NULL){
p->right->left = p->left;
}
else{
tail = p->left;
}
p->left = NULL;
p->right = NULL;
}
void insert(Node *p){
if(head == NULL){
head = tail = p;
}
else{
tail->right = p;
p->left = tail;
tail = p;
}
}
int get(int key) {
if(key_address.find(key) == key_address.end()){
return -1;
}
Node *add = key_address[key];
delete_node(add);
insert(add);
return add->val;
}
void put(int key, int value) {
Node *new_node = new Node(key,value);
if(key_address.find(key)!=key_address.end()){
key_address[key]->val = value;
delete_node(key_address[key]);
insert(key_address[key]);
}
else{
key_address[key]=new_node;
if(size==capacity){
key_address.erase(head->key);
delete_node(head);
insert(new_node);
}
else{
size++;
insert(new_node);
}
}
}
};
/**
* 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);
*/