LRU的实现
LRU的c++实现,使用的是双向链表+map。
链接: [https://blog.csdn.net/weixin_43819197/article/details/95901964).
#ifndef _LRU_H
#define _LRU_H
#include<map>
class CatchLRU
{
public:
CatchLRU(int size);
~CatchLRU();
struct CatchNode
{
int key;
CatchNode *pre,*next;
CatchNode(int k):key(k),pre(NULL),next(NULL){}
};
void remove(CatchNode* node);
void pushHeaad(int key);
int getKey(const int key);
void print();
private:
std::map<int,CatchNode*> mp; //节点存储
int catchSize; //LRU缓存大小
CatchNode* head;// 记录头指针
CatchNode* tail;//记录尾指针
};
#endif
#include "LRU.h"
#include <algorithm>
#include <iostream>
using namespace std;
CatchLRU::CatchLRU(int size):catchSize(size)
{
head=NULL;
tail=NULL;
}
CatchLRU::~CatchLRU()
{
mp.clear();//释放链表
}
//删除节点
void CatchLRU::remove(CatchNode* node)
{
if (node == NULL)
return;
if (node->pre == NULL)
{
if (node->next != NULL)
{
node->next->pre = NULL;
head = node->next;
}
}
else
{
node->pre->next = node->next;
}
if (node->next != NULL)
{
node->next->pre = node->pre;
}
else
{
if (node->pre != NULL)
{
node->pre->next = NULL;
tail = node->pre;
}
}
delete node;
}
//将head装入catch
void CatchLRU::pushHeaad(int key)
{
map<int,CatchNode*>::iterator iter=mp.find(key);
if(iter==mp.end())//若节点不在map中
{
if(mp.size()==catchSize)
{
auto it=mp.find(tail->key);//先找到尾结点
remove(tail);//从双向链表中移除尾节点(最近未使用)
mp.erase(it);//从map中移除key
}
}
else//节点在map中
{
remove(iter->second);//相当于更新最近使用时间
mp.erase(iter);
}
//插入新的key
CatchNode* p=new CatchNode(key);
p->next=head;
p->pre=NULL;
if(head==NULL)//初始化头结点
{
head=p;
}
else
{
head->pre=p;
head=p;
}
if(tail==NULL)//初始化尾结点(初始化头尾相连,只有一个节点)
{
tail=head;
}
mp[key]=p;
}
int CatchLRU::getKey(const int key)
{
map<int,CatchNode*>::iterator it=mp.find(key);
if(it!=mp.end())
{
return it->second->key;
}
else
{
return -1;
}
}
void CatchLRU::print()
{
CatchNode* p = head;
while (p != NULL)
{
cout << p->key << "_";
p = p->next;
}
//cout << p->key << std::endl;
}
int main()
{
CatchLRU* catchTest = new CatchLRU(10);
for(int i = 0; i < 13; i++)
catchTest->pushHeaad(i);
catchTest->pushHeaad(3);
catchTest->print();
system("pause");
return 0;
}