思路
参考自LRU 策略详解和实现
采用的数据结构:双向哈希链表
代码
#include<iostream>
#include<algorithm>
#include<unordered_map>
using namespace std;
struct Node
{
int key;
int value;
Node* pre;
Node* next;
//构造函数初始化
Node(int key, int value) :key(key), value(value), pre(nullptr), next(nullptr) {}
};
class LRUCache {
private:
int size;//缓冲区大小
Node* head;//头节点
Node* tail;//未节点
unordered_map<int, Node*> p;//哈希表
public:
LRUCache(int capacity) {
this->size = capacity;
head = nullptr;
tail = nullptr;
}
//获取缓冲区的key对应的value
int get(int key) {
//当该key存在
if (p.count(key) > 0) {
//删除该key对应的原来节点
Node* cur = p[key];
int value = cur->value;
remove(cur);//仅删除哈希双向链表中的节点,不必删除哈希表中的
setHead(cur);//将节点重新插入到缓冲区的头部
return value;
}
return -1;//当该值不存在时
}
void put(int key, int value) {
//当该key值存在
if (p.count(key) > 0) {
//删除该key对应的原来节点
Node* cur = p[key];
cur->value = value;
remove(cur);//
setHead(cur);//将节点重新插入到缓冲区的头部
}
else {//当该key值不存在
Node* node = new Node(key, value);//这里的内存泄露如何处理?
//判断当前缓冲区大小是否已满
if (p.size() >= size) {
//删除尾部节点
unordered_map<int, Node*>::iterator it = p.find(tail->key);//返回迭代器类型
remove(tail);
p.erase(it);//erase的函数参数使迭代器类型,所以上面需要使用迭代器类型
}
//将新节点插入到缓冲区头部
setHead(node);
p[key] = node;
}
}
//删除当前节点
void remove(Node* cur) {
//当前节点是head
if (cur == head)
head = cur->next;
else if (cur == tail) //当前节点是tail
tail = cur->pre;
else {
cur->pre->next = cur->next;
cur->next->pre = cur->pre;
}
//delete cur;//删除节点
}
// 将当前节点插入到头部
void setHead(Node* cur) {
cur->next = head;
if (head != nullptr)
head->pre = cur;
head = cur;//更新head
if (tail == nullptr) tail = head;
}
};