完整基于 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;
}
}

最新文章

  1. php预定义$_SERVER实例,所有$_SERVER开头的都是预定义服务变量。
  2. service的简单使用
  3. C# 事件编程在游戏开发的应用
  4. mysql workbench建表时PK,NN,UQ,BIN,UN,ZF,AI
  5. SpringMVC系列之基本配置
  6. ios CoreBluetooth 警告 is being dealloc&#39;ed while pending connection
  7. ajax 请求
  8. css 控制滚动样式
  9. mysql sqlmap 注入尝试
  10. eclipse 配置android sdk和maven
  11. Openstack Swift 原理、架构与 API 介绍
  12. 【C++】const &amp; 指针
  13. 独立安装CentOS7.4全记录
  14. mysql常见问题解决
  15. Python数据类型补充1
  16. Win10系列:UWP界面布局进阶4
  17. 鼠标移上去触动hover致使div向上移动几个相素(动画transition轻轻的移动)
  18. 1、从C语言到C++
  19. Spark(Hive) SQL中UDF的使用(Python)【转】
  20. 1070 Mooncake (25 分)

热门文章

  1. Redis入门学习(二):下载安装
  2. Finished with error: ProcessException: Process &quot;D:\FlutterAPP\flutter_appfive\android\gradlew.bat&quot; exited abnormally:
  3. pandas 之 datetime 初识
  4. pandas 之 交叉表-透视表
  5. docker研究-6 dockerfile 介绍使用
  6. 【微信小程序】开发实战 之 「视图层」WXML &amp; WXSS 全解析
  7. 201871010110-李华《面向对象程序设计(java)》第十周学习总结
  8. 【视频技术】EasyDarwin
  9. woocommerce如何隐藏SKU
  10. sqler 2.2 发布了,支持定时任务以及触发器