LRU缓存机制
struct DListNode{
int key,value;
DListNode* pre,*next;
DListNode():key(0),value(0),pre(nullptr),next(nullptr){}
DListNode(int _key,int _value):key(_key),value(_value),pre(nullptr),next(nullptr){}
};
class LRUCache {
public:
LRUCache(int capacity) {
head=new DListNode();
tail=new DListNode();
head->next=tail;
tail->pre=head;
this->capacity=capacity;
}
void removeTail()
{
DListNode* p=tail->pre;
p->pre->next=tail;
tail->pre=p->pre;
delete p;
p=nullptr;
}
void moveToHead(DListNode* p)
{
p->next->pre=p->pre;
p->pre->next=p->next;
addToHead(p);
}
void addToHead(DListNode* p)
{
p->next=head->next;
p->pre=head;
p->next->pre=p;
head->next=p;
}
int get(int key) {
if(um.count(key))
{
moveToHead(um[key]);
return um[key]->value;
}
else return -1;
}
void put(int key, int value) {
if(um.count(key)){
moveToHead(um[key]);
um[key]->value=value;
}
else{
if(um.size()>=capacity)
{
um.erase(tail->pre->key);
removeTail();
}
DListNode* p=new DListNode(key,value);
um.insert(make_pair(key,p));
addToHead(p);
}
}
private:
DListNode* head;
DListNode* tail;
unordered_map<int,DListNode*> um;
int capacity;
};
/**
* 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);
*/