LRU

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值