PHP实现LRU算法的原理详解
1.概念
LRU : 最近最少使用算法
2.代码
key = $key; $this->value = https://www.it610.com/article/$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="https://www.it610.com/article/.$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总结 【PHP实现LRU算法的原理详解】本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注脚本之家的更多内容!
key=evalue=https://www.it610.com/article/eeeeeeeeeeee
key=dvalue=https://www.it610.com/article/dddddddddddd
key=cvalue=https://www.it610.com/article/ccccccccccc
推荐阅读
- C语言|库函数《qsort》的模拟实现,原来如此简单
- c语言初学之路|【C语言】模拟实现库函数 strcpy(复制字符串内容) 与 strlen(求字符串长度)
- c语言|C语言中库函数的模拟实现
- c语言|(C语言)strstr库函数的简单使用以及模拟实现
- c语言|C语言-字符串库函数详解(含部分函数的模拟实现)
- Qt学习|Qt学习之使用QTableWiget实现简易五子棋游戏(人机对战)
- Linux|Linux socket编程(C语言socket实现客户端与服务器网络通信)
- vue中基于sortablejs与el-upload实现文件上传后拖拽排序
- 钉钉机器人实现异常预警通知功能
- mac 下 pecl 的 扩展配置 ( 基于php@7.4 )