LRU的实现

博客介绍了LRU的C++实现,采用双向链表与map结合的方式,还提及了LRU.h和LRU.cpp文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值