#基本实现是用一个双向链表来保存节点,同时使用Hashtable来保存每个节点的映射关系
import java.util.*;
class LRUCache {
class DListNode{
int value;
int key;
DListNode pre;
DListNode post;
}
public void addNode(DListNode node){
node.pre=head;
node.post=head.post;
head.post.pre=node;
head.post=node;
}
public void removeNode(DListNode node){
DListNode pre=node.pre;
DListNode post=node.post;
pre.post=post;
post.pre=pre;
}
public void moveToHead(DListNode node){
removeNode(node);
addNode(node);
}
public DListNode poolTail(){
DListNode result=tail.pre;
removeNode(result);
return result;
}
private int count;
private DListNode head;
private DListNode tail;
private Hashtable<Integer,DListNode> cache=new Hashtable<Integer,DListNode>();
private int capacity;
public LRUCache(int capacity) {
this.capacity=capacity;
this.count=0;
head=new DListNode();
head.pre=null;
tail=new DListNode();
tail.post=null;
head.post=tail;
tail.pre=head;
}
public int get(int key) {
DListNode node=cache.get(key);
if(node==null){
return -1;
}
moveToHead(node);
return node.value;
}
public void put(int key, int value) {
DListNode node=cache.get(key);
if(node==null){
DListNode cur=new DListNode();
cur.key=key;
cur.value=value;
cache.put(key,cur);
addNode(cur);
count++;
if(count>capacity){
DListNode last=poolTail();
cache.remove(last.key);
count--;
}
}else{
node.value=value;
moveToHead(node);
}
}
}