题目
思路
创建一个新的数据结构,双向链表。从头结点插入新的数据,从尾节点删除数据。通过缓存数据的键映射到其在双向链表中的位置。为了在添加节点和删除节点时避免检查相邻的节点是否存在,可以使用一个伪头部和伪尾部来标记界限。
代码
class LRUCache {
public:
struct Node{
int key,value;
Node* prev;
Node* next;
Node():key(0),value(0),prev(nullptr),next(nullptr){}
Node(int _key,int _value):key(_key),value(_value),prev(nullptr),next(nullptr){}
};
Node *head,*tail;
int size=0,capacity;
unordered_map<int,Node*> map;
LRUCache(int _capacity) {
capacity = _capacity;
head = new Node();
tail = new Node();
head->next=tail;
tail->prev=head;
}
void addtoHead(Node* cur){
cur->next=head->next;
head->next->prev=cur;
head->next=cur;
cur->prev=head;
}
void removeNode(Node* cur){
cur->next->prev=cur->prev;
cur->prev->next=cur->next;
}
void movetoHead(Node* cur){
removeNode(cur);
addtoHead(cur);
}
int get(int key) {
if(!map.count(key)) return -1;
Node* cur=map[key];
movetoHead(cur);
return map[key]->value;
}
void put(int key, int value) {
if(map.count(key)){
map[key]->value=value;
movetoHead(map[key]);
}
else{
Node* cur=new Node(key,value);
map[key]=cur;
addtoHead(cur);
if(++size>capacity){
map.erase(tail->prev->key);
tail->prev=tail->prev->prev;
tail->prev->next=tail;
size--;
}
}
return;
}
};