实现LRU算法
class myListNode{
public:
int key;
int val;
myListNode* pre;
myListNode* next;
myListNode() : key(0),val(0),pre(nullptr),next(nullptr) {}
myListNode(int _key,int _val) : key(_key),val(_val),pre(nullptr),next(nullptr) {}
};
class LRUCache {
private:
unordered_map<int,myListNode*> hash;
myListNode* head;
myListNode* tail;
int capacity;
int size;
public:
LRUCache(int _capacity) : capacity(_capacity),size(0) {
head = new myListNode();
tail = new myListNode();
head->next = tail;
tail->pre = head;
}
int get(int key) {
auto it = hash.find(key);
if(it == hash.end()) return -1;
else {
myListNode* currentNode = hash[key];
RemoveNode(currentNode);
AddToHead(currentNode);
return currentNode->val;
}
}
void put(int key, int value) {
auto it = hash.find(key);
if(it == hash.end()) {
myListNode* currentNode = new myListNode(key,value);
AddToHead(currentNode);
hash.insert(make_pair(key,currentNode));
size++;
if(size > capacity) {
RemoveTail();
size--;
}
}
else {
myListNode* currentNode = hash[key];
currentNode->val = value;
RemoveNode(currentNode);
AddToHead(currentNode);
}
}
void RemoveNode(myListNode* currentNode) {
currentNode->next->pre = currentNode->pre;
currentNode->pre->next = currentNode->next;
currentNode->next = nullptr;
currentNode->pre = nullptr;
}
void AddToHead(myListNode* currentNode) {
head->next->pre = currentNode;
currentNode->next = head->next;
head->next = currentNode;
currentNode->pre = head;
}
void RemoveTail(){
myListNode* currentNode = tail->pre;
currentNode->pre->next = tail;
tail->pre = currentNode->pre;
hash.erase(currentNode->key);
delete currentNode;
currentNode = nullptr;
}
};