#include<stdio.h>
#include<map>
#include<unordered_map>
using namespace std;
struct DLinkedNode {
int key;
int value;
DLinkedNode* pre;
DLinkedNode* next;
DLinkedNode() :key(0), value(0), pre(nullptr), next(nullptr) {};
DLinkedNode(int _key, int _value) :key(_key), value(_value), pre(nullptr), next(nullptr) {};
};
class LRUCache
{
private:
unordered_map<int, DLinkedNode*> cache;
DLinkedNode* head;
DLinkedNode* tail;
int size;
int capacity;
public:
LRUCache(int _capacity)
{
capacity = _capacity;
size = 0;
head = new DLinkedNode();
tail = new DLinkedNode();
head->next = tail;
tail->pre = head;
}
int get(int key)
{
if (!cache.count(key))
return -1;
else
MoveToHead(cache[key]);
return cache[key]->value;
}
void put(int key, int value)
{
if (cache.count(key))
{
cache[key]->value = value;
MoveToHead(cache[key]);
}
else
{
DLinkedNode* node = new DLinkedNode(key, value);
cache[key] = node;
addHead(node);
size++;
if (size > capacity)
{
DLinkedNode* removed = RemoveLast();
cache.erase(removed->key);
delete removed;
size--;
}
}
}
void removeNode(DLinkedNode* node)
{
node->pre->next = node->next;
node->next->pre = node->pre;
}
void addHead(DLinkedNode* node)
{
head->next->pre = node;
node->next = head->next;
head->next = node;
node->pre = head;
}
void MoveToHead(DLinkedNode* node)
{
removeNode(node);
addHead(node);
}
DLinkedNode* RemoveLast()
{
DLinkedNode* node = tail->pre;
removeNode(node);
return node;
}
};
|