LRU(c++实现)
链接:https://leetcode-cn.com/problems/lru-cache/
struct DLinkedNode{
int key,value;
DLinkedNode* prev;
DLinkedNode* next;
DLinkedNode():key(0),value(0),prev(nullptr),next(nullptr){}
DLinkedNode(int _key,int _value):key(_key),value(_value),prev(nullptr),next(nullptr){}
};
class LRUCache {
private:
unordered_map<int,DLinkedNode*> cache;
DLinkedNode* head;//表头
DLinkedNode* tail;//表尾
int size;//当前长度
int capacity;//缓存长度限制
public:
LRUCache(int _capacity) {
size = 0;
capacity = _capacity;
head = new DLinkedNode();
tail = new DLinkedNode();
head->next = tail;
tail->prev = tail;
}
//查找有没有key
int get(int key) {
if(!cache.count(key)){
return -1;
}
//如果 key 存在,先通过哈希表定位,再移到头部
DLinkedNode* node = cache[key];
moveToHead(node);
return node->value;
}
void put(int key, int value) {
if(!cache.count(key)){
//如果 key 不存在的话,就建一个新节点
DLinkedNode* node = new DLinkedNode(key,value);
//加入hash表
cache[key] = node;
//添加到链表的头部
addToHead(node);
++size;
//如果超出容量
if(size > capacity){
//删除尾部节点
DLinkedNode* removed = removeTail();
//
cache.erase(removed->key);
delete removed;
--size;
}
}
else{
//如果 key 存在,就通过hash表定位,然后更新value
DLinkedNode* node = cache[key];
node->value = value;
moveToHead(node);
}
}
//把node加到头部
void addToHead(DLinkedNode* node){
node->prev = head;
node->next = head->next;
head->next->prev = node;
head->next = node;
}
//删掉node
void removeNode(DLinkedNode* node){
node->prev->next = node->next;
node->next->prev = node->prev;
}
//删掉node并加到头部
void moveToHead(DLinkedNode* node){
removeNode(node);
addToHead(node);
}
//删掉尾部节点并返回
DLinkedNode* removeTail(){
DLinkedNode* node = tail->prev;
removeNode(node);
return 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);
*/