手写LRU实现
2024-09-08 14:37:56
完整基于 Java 的代码参考如下
class DLinkedNode {
String key;
int value;
DLinkedNode pre;
DLinkedNode post;
}
LRU Cache
public class LRUCache { private Hashtable<Integer, DLinkedNode>
cache = new Hashtable<Integer, DLinkedNode>();
private int count;
private int capacity;
private DLinkedNode head, tail; public LRUCache(int capacity) {
this.count = 0;
this.capacity = capacity; head = new DLinkedNode();
head.pre = null; tail = new DLinkedNode();
tail.post = null; head.post = tail;
tail.pre = head;
} public int get(String key) { DLinkedNode node = cache.get(key);
if(node == null){
return -1; // should raise exception here.
} // move the accessed node to the head;
this.moveToHead(node); return node.value;
} public void set(String key, int value) {
DLinkedNode node = cache.get(key); if(node == null){ DLinkedNode newNode = new DLinkedNode();
newNode.key = key;
newNode.value = value; this.cache.put(key, newNode);
this.addNode(newNode); ++count; if(count > capacity){
// pop the tail
DLinkedNode tail = this.popTail();
this.cache.remove(tail.key);
--count;
}
}else{
// update the value.
node.value = value;
this.moveToHead(node);
}
}
/**
* Always add the new node right after head;
*/
private void addNode(DLinkedNode node){
node.pre = head;
node.post = head.post; head.post.pre = node;
head.post = node;
} /**
* Remove an existing node from the linked list.
*/
private void removeNode(DLinkedNode node){
DLinkedNode pre = node.pre;
DLinkedNode post = node.post; pre.post = post;
post.pre = pre;
} /**
* Move certain node in between to the head.
*/
private void moveToHead(DLinkedNode node){
this.removeNode(node);
this.addNode(node);
} // pop the current tail.
private DLinkedNode popTail(){
DLinkedNode res = tail.pre;
this.removeNode(res);
return res;
}
}
最新文章
- php预定义$_SERVER实例,所有$_SERVER开头的都是预定义服务变量。
- service的简单使用
- C# 事件编程在游戏开发的应用
- mysql workbench建表时PK,NN,UQ,BIN,UN,ZF,AI
- SpringMVC系列之基本配置
- ios CoreBluetooth 警告 is being dealloc&#39;ed while pending connection
- ajax 请求
- css 控制滚动样式
- mysql sqlmap 注入尝试
- eclipse 配置android sdk和maven
- Openstack Swift 原理、架构与 API 介绍
- 【C++】const &; 指针
- 独立安装CentOS7.4全记录
- mysql常见问题解决
- Python数据类型补充1
- Win10系列:UWP界面布局进阶4
- 鼠标移上去触动hover致使div向上移动几个相素(动画transition轻轻的移动)
- 1、从C语言到C++
- Spark(Hive) SQL中UDF的使用(Python)【转】
- 1070 Mooncake (25 分)
热门文章
- Redis入门学习(二):下载安装
- Finished with error: ProcessException: Process ";D:\FlutterAPP\flutter_appfive\android\gradlew.bat"; exited abnormally:
- pandas 之 datetime 初识
- pandas 之 交叉表-透视表
- docker研究-6 dockerfile 介绍使用
- 【微信小程序】开发实战 之 「视图层」WXML &; WXSS 全解析
- 201871010110-李华《面向对象程序设计(java)》第十周学习总结
- 【视频技术】EasyDarwin
- woocommerce如何隐藏SKU
- sqler 2.2 发布了,支持定时任务以及触发器