PHP简单实现LRU算法原理

  1. 概念
    LRU : 最近最少使用算法

  2. 代码

<?php
class Node
{
    public $preKey = null; //链表前一个节点
    public $nextKey = null;  //链表后一个节点
    public $key= null;      //当前的值
    public $value= null;    //当前key

    public function __construct($key,$value){
        $this->key = $key;
        $this->value = $value;
    }

    public function setPre($preKey)
    {
        $this->preKey = $preKey;
    }

    public function setNext($nextKey)
    {
        $this->nextKey = $nextKey;
    }
}

class LRUCache{
    public $cacheTable = [];
    /** Node null  */
    private $headNode = null;
    private $lastNode = null;
    private $cacheCount = 0;
    private $cacheMax = 3;

    public function addNode($key,$value)  //此处采用头插法
    {
        $addNode = new Node($key,$value);
        if ( !empty($this->headNode))
        {
            $this->headNode->preKey = $addNode; //如果链表存在,将节点添加到节点前一个
        }
        $addNode->nextKey = $this->headNode;

        //第一次保存最后一个节点为头结点
        if ($this->lastNode == null){
            $this->lastNode = $addNode;
        }

        $this->headNode = $addNode;
        $this->cacheTable[$key] = $addNode;
        $this->cacheCount++;

    }

    public function set($key,$value)
    {
        //先判断是否需要删除
        $this->shiftNode();
        $this->addNode($key,$value);
        return true;
    }

    //自动删除
    public function shiftNode()
    {
        while ($this->cacheCount >= $this->cacheMax){
            if (!empty($this->lastNode)){
                if ($this->lastNode->preKey){
                    $this->lastNode->preKey->nextKey = null;
                    $this->lastNode = $this->lastNode->preKey;
                }

                unset($this->cacheTable[$this->lastNode->key]);
            }
            $this->cacheCount --;
        }
    }

    public function dumpAllData()
    {
        $node = $this->headNode;
        while (($node)){
            echo "key=".$node->key."value=".$node->value."\n";
            $node = $node->nextKey;
        }
    }

}


$Cache = new LRUCache();
$Cache->set("a","aaaaaaaaaaa");
$Cache->set("b","bbbbbbbbbbb");
$Cache->set("c","ccccccccccc");
$Cache->set("d","dddddddddddd");
$Cache->set("e","eeeeeeeeeeee");
//$Cache->set("f","ffffffffffff");
$Cache->dumpAllData();
//var_dump($Cache);  //是一个深度的数组(对象)



  1. 结果
[root@VM-16-13-centos ~]# php LRU.php 
key=evalue=eeeeeeeeeeee
key=dvalue=dddddddddddd
key=cvalue=ccccccccccc
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值