struct LinkNode{
int _key;
int _value;
LinkNode* prev;
LinkNode* next;
LinkNode() : _key(0), _value(0), prev(nullptr), next(nullptr) {}
LinkNode(int key, int value): _key(key), _value(value), prev(nullptr), next(nullptr) {}
};
class LRUCache {
private:
unordered_map<int, LinkNode*> cache;
LinkNode* head;
LinkNode* tail;
int _size;
int _capacity;
void remove(LinkNode* x){
x->prev->next = x->next;
x->next->prev = x->prev;
}
void push_front(LinkNode* x){
x->prev = head;
x->next = head->next;
head->next->prev = x;
head->next = x;
}
LinkNode* get_node(int key){
auto it = cache.find(key);
if(it == cache.end()){
return nullptr;
}
auto node = it->second;
remove(node);
push_front(node);
return node;
}
public:
LRUCache(int capacity) {
_capacity = capacity;
_size = 0;
head = new LinkNode();
tail = new LinkNode();
head->next = tail;
tail->prev = head;
}
int get(int key) {
auto node = get_node(key);
return node ? node->_value : -1;
}
void put(int key, int value) {
auto node = get_node(key);
if(node){
node->_value = value;
//push_front(node);
return;
}
LinkNode* onenode = new LinkNode(key, value);
cache.insert(make_pair(key, onenode));
push_front(onenode);
_size++;
if(_size > _capacity){
auto back_node = tail->prev;
cache.erase(back_node->_key);
_size--;
remove(back_node);
delete back_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);
*/
07-23
444
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
07-21
363
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)