LRU的c++实现,使用的是双向链表+map。
LRU.h
#ifndef _LRU_H
#define _LRU_H
#include <map>
class CatchLRU
{
public:
CatchLRU(int size);
~CatchLRU();
struct CatchNode
{
int key;
//int value;
CatchNode *pre, *next;
CatchNode(int k) :key(k),pre(NULL),next(NULL){
}
};
void remove(CatchNode* node);
void pushHead(int key);
int getKey(const int key);
void print();
private:
std::map<int, CatchNode*> mp; //节点存储
int catchsize; //LRU缓存的大小
CatchNode* head; //记录头指针
CatchNode* tail; //记录尾指针
};
#endif // !_LRU_H
LRU.cpp
#include "LRU.h"
#include <map>
#include <algorithm>
#include <iostream>
CatchLRU::CatchLRU(int size):catchsize(size)
{
head = NULL;
tail = NULL;
//catchsize = 0;
}
CatchLRU::~CatchLRU()
{
mp.clear();
//释放链表
}
//删除节点
void CatchLRU::remove(CatchNode* node)
{
if (node == NULL)
return;
if (node->pre != NULL)
{
node->pre->next = node->next;
//node->next->pre = node->pre;
}
else
{
node->next->pre = NULL;
head = node->next;
}
if (node->next != NULL)
{
node->next->pre = node->pre;
}
else
{
node->pre->next = NULL;
tail = node->pre;
}
delete node;
}
//将head装入catch
void CatchLRU::pushHead(int key)
{
std::map<int, CatchNode*>::iterator iter = mp.find(key);
if (iter == mp.end())
{
if (mp.size() == catchsize)
{
auto it = mp.find(tail->key);
remove(tail);
mp.erase(it);
}
}
else
{
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)
{
std::map<int, CatchNode*>::iterator iter = mp.find(key);
if (iter == mp.end())
{
return iter->second->key;
}
else
return -1;
}
void CatchLRU::print()
{
CatchNode* p = head;
while (p->next != NULL)
{
std::cout << p->key << "→";
p = p->next;
}
std::cout << p->key << std::endl;
}
int main()
{
CatchLRU* catchTest = new CatchLRU(10);
for(int i = 0; i < 13; i++)
catchTest->pushHead(i);
catchTest->pushHead(3);
catchTest->print();
system("pause");
return 0;
}