package lru;

import java.util.HashMap;

public class LRUCache2<K,V> {
public final int capacity;
class DNode{
K key;
V value;
DNode next;
DNode pre;
public DNode(K key, V value, LRUCache2<K, V>.DNode pre, LRUCache2<K, V>.DNode next) {
super();
this.key = key;
this.value = value;
this.pre = pre;
this.next = next;
} }

  //附加头结点
DNode head=new DNode(null,null,null,null);
DNode last=head; HashMap<K,DNode> map=new HashMap<>(); public LRUCache2(int capacity) {
this.capacity=capacity;
} public V get(K key) {
DNode node=map.get(key);
if(node!=null) {
moveToHead(node);
}
return node==null?null:node.value;
} public void put(K key, V value) {
DNode node=map.get(key);
if(node==null) {
if(map.size()>=capacity) {
removeLast();
}
node=new DNode(key, value,head,head.next);
if(head.next!=null)
head.next.pre=node;
head.next=node;
map.put(node.key, node);
if(last==head) last=node;
}else {
node.value=value;
moveToHead(node);
} }
private void removeLast() {
// TODO Auto-generated method stub
if(last==null) {
throw new IllegalArgumentException("cant remove before put");
}
map.remove(last.key);
last.pre.next=null;
last=last.pre;
} private void moveToHead(LRUCache2<K, V>.DNode node) {
// TODO Auto-generated method stub
if(head.next==node) return;
if(last==node) {
last=node.pre;
}
node.pre.next=node.next;
if(node.next!=null) node.next.pre=node.pre;
node.next=head.next;
node.pre=head;
head.next.pre=node;
head.next=node;
}
}

最新文章

  1. php自动载入类的实践
  2. ASP.NET中获取当日,当周,当月,当年的日期
  3. html 补充
  4. C语言位运算详解[转]
  5. IOS开发-表单控件的应用
  6. Tmall Programmer Triples Smartisan Sales
  7. python中的super
  8. C#学习日志 day7 --------------LINQ与Lamda语句的初步尝试以及XML的生成
  9. 优化php性能的一点总结
  10. Sharding-jdbc实现分库分表
  11. HTML/CSS初步了解
  12. Error fetching https://gems.ruby-china.org/: bad response Not Found 404 (https://gems.ruby-china.org/specs.4.8.gz) 报错解决办法
  13. P1495 曹冲养猪
  14. 开源的电商 B2C、B2B2C 电商系统-关于shopnc版权问题处处是陷阱啊
  15. SpringMVC(十五) RequestMapping map模型数据
  16. mysql_day04
  17. ping内网一台虚拟机延时很大(hyper-v虚拟机)的解决办法
  18. 8大排序算法总结 JS 实现
  19. android studio下生成jni头文件
  20. (转) C++中成员初始化列表的使用

热门文章

  1. module in JavaScript
  2. jquery.qrcode笔记
  3. 脸书VS微软,为何“老年创业者”更担忧AI失控?
  4. 使用powerdesigner进行数据库设计
  5. Mysql SQL Mode简介
  6. C++扬帆远航——12(抓小偷)
  7. PyQt5之音乐播放器
  8. APM监控工具Pinpoint搭建
  9. 用vue + leancloud开发一个免费的博客
  10. Ios/Android h5 唤起本地APP