-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLRUCache.cpp
More file actions
executable file
·143 lines (124 loc) · 2.82 KB
/
LRUCache.cpp
File metadata and controls
executable file
·143 lines (124 loc) · 2.82 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
133
134
135
136
137
138
139
140
141
142
143
//
// LRUCache.cpp
// leetcode
//
// Created by witwolf on 3/30/15.
// Copyright (c) 2015 witwolf. All rights reserved.
//
#include <iostream>
#include <list>
#include <map>
#include <utility>
using namespace std;
struct Node{
Node(int v){
value = v;
prev = next = NULL;
}
int value;
Node * prev;
Node * next;
} ;
class DoubleLinkList{
public:
DoubleLinkList(int capacity):head(NULL),tail(NULL),_capacity(capacity),_size(0){}
int size(){
return _size;
}
Node * front(){
return head;
}
void pop_front(){
this->erase(head);
}
void erase(Node *node){
Node* prev = node->prev;
Node* next = node->next;
if(prev){
prev->next = next;
}else{
head = next;
}
if(next){
next->prev = prev;
}else{
tail = prev;
}
_size -= 1;
delete node;
}
Node * push_back(int value){
Node * node = new Node(value);
if(tail == NULL){
head = tail = node;
}else{
tail->next = node;
node->prev = tail;
tail = node;
}
_size += 1;
return node;
}
private:
int _size;
int _capacity;
Node* head;
Node* tail;
};
class LRUCache{
public:
LRUCache(int capacity):keys(capacity) {
this->capacity = capacity;
}
int get(int key) {
auto it = kv.find(key);
if (it != kv.end()){
keys.erase(it->second.second);
it->second.second = keys.push_back(key);
return it->second.first;
}
return -1;
}
void set(int key, int value) {
auto it = kv.find(key);
if(it != kv.end()){
keys.erase(it->second.second);
it->second.second = keys.push_back(key);
it->second.first = value;
}else{
if(keys.size() == capacity){
kv.erase(keys.front()->value);
keys.pop_front();
}
Node * node = keys.push_back(key);
kv[key] = make_pair(value, node);
}
}
private:
map<int,pair<int,Node*> > kv;
DoubleLinkList keys;
int capacity;
};
int main(int argc,char **argv){
DoubleLinkList dll(10);
Node * node1 = dll.push_back(5);
Node * node2 = dll.push_back(2);
Node * node3 = dll.push_back(2);
Node * node4 = dll.push_back(2);
Node * node5 = dll.push_back(2);
Node * node6 = dll.push_back(2);
Node * node7 = dll.push_back(2);
dll.erase(node2);
dll.erase(node5);
dll.pop_front();
dll.erase(node7);
dll.erase(node4);
LRUCache lru(2);
lru.get(2);
lru.set(2,6);
lru.get(1);
lru.set(1,5);
lru.set(1,2);
lru.get(1);
lru.get(2);
}