struct DLinkedNode{
int key;
int value;
DLinkedNode *next;
DLinkedNode *prev;
DLinkedNode():key(0), value(0), next(nullptr), prev(nullptr){}
DLinkedNode(int _key, int _value):key(_key), value(_value), next(nullptr), prev(nullptr){};
};
class LRUCache {
private:
int _capacity; //记录双向链表容量
DLinkedNode *dummyHead;
DLinkedNode *dummyTail;
int size; //记录当前有多少个元素
unordered_map<int, DLinkedNode*> map;
public:
//构造函数
LRUCache(int capacity): _capacity(capacity), size(0){
dummyHead = new DLinkedNode();
dummyTail = new DLinkedNode();
dummyTail->prev = dummyHead;
dummyHead->next = dummyTail;
}
int get(int key) {
//找不到
if(map.count(key)==0)
return -1;
//找到,调整到链表头部
DLinkedNode *node = map[key];
moveToHead(node);
return node->value;
}
void put(int key, int value) {
//已经存在,更新值,移至链表头部
if(map.count(key)==1){
DLinkedNode *node = map[key];
node->value = value;
moveToHead(node);
}
//不存在:1.没到容量,直接插入;2.已满,先删除,再插入
else{
DLinkedNode *node = new DLinkedNode();
node->key = key;
node->value = value;
map[key] = node;
size++;
//还没满,可以直接插入
if(size<=_capacity){
addToHead(node);
}
//满了,先删除,再插入,释放删除节点所占内存
else{
DLinkedNode *removeNode = removeTail();
map.erase(removeNode->key);
addToHead(node);
delete removeNode;
size--;
}
}
}
void addToHead(DLinkedNode *node){
node->next = dummyHead->next;
node->prev = dummyHead;
dummyHead->next->prev = node;
dummyHead->next = node;
}
void removeNode(DLinkedNode *node){
node->prev->next = node->next;
node->next->prev = node->prev;
}
void moveToHead(DLinkedNode *node){
removeNode(node);
addToHead(node);
}
//删除尾部节点,但是同时要删除哈希表中的节点,所以要返回值
DLinkedNode *removeTail(){
DLinkedNode *node = dummyTail->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);
*/
|