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); //是一个深度的数组(对象)
结果
[root@VM-16-13-centos ~]# php LRU.php
key=evalue=eeeeeeeeeeee
key=dvalue=dddddddddddd
key=cvalue=ccccccccccc
总结
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注编程学习网的更多内容!
沃梦达教程
本文标题为:PHP实现LRU算法的原理详解
基础教程推荐
猜你喜欢
- PHP中的错误及其处理机制 2023-06-04
- PHP命名空间简单用法示例 2022-12-01
- laravel ORM关联关系中的 with和whereHas用法 2023-03-02
- PHP获取MySQL执行sql语句的查询时间方法 2022-11-09
- 使用PHP开发留言板功能 2023-03-13
- laravel 解决多库下的DB::transaction()事务失效问题 2023-03-08
- thinkphp3.2.3框架动态切换多数据库的方法分析 2023-03-19
- PHP实现Redis单据锁以及防止并发重复写入 2022-10-12
- php array分组,PHP中array数组的分组排序 2022-08-01
- 在Laravel中实现使用AJAX动态刷新部分页面 2023-03-02