public static class Node<V>{
public V value;
public Node<V> last;
public Node<V> next;
public Node(V value) {
this.value=value;
}
}
public static class NodeDoubleLinkedList<V>{
//自制一个双向链表
private Node<V>head;
private Node<V>tail;
public NodeDoubleLinkedList() {
this.head=null;
this.tail=null;
}
public void addNode(Node<V>newNode) {
if (newNode==null) {
//传进来的是个空值,不管
return;
}
if(this.head==null) {
//原来链表为空
this.head=newNode;
this.tail=newNode;
}else {
this.tail.next=newNode;
newNode.last=this.tail;
this.tail=newNode;
}
}
public void moveNodeToTail(Node<V>node) {
if(this.tail==node) {
//待移动的节点在末尾
return;
}
if(this.head==node) {
//待移动的节点是头节点
this.head=node.next;
this.head.last=null;
}else {
node.last.next=node.next;
node.next.last=node.last;
}
node.last=this.tail;
node.next=null;
this.tail.next=node;
this.tail=node;
}
public Node<V>removeHead(){
if(this.head==null) {
return null;
}
Node<V>res=this.head;
if(this.head==this.tail) {
//只有一个节点
this.head=null;
this.tail=null;
}else {
this.head=res.next;
res.next=null;
this.head.last=null;
}
return res;
}
}
public static class MyCache<K,V>{
private HashMap<K,Node<V>>keyNodeMap;
private HashMap<Node<V>,K>NodeKeyMap;
private NodeDoubleLinkedList<V>nodeList;
private int capacity;
public MyCache(int capacity) {
if(capacity<1) {
throw new RuntimeException("should be more than 0.");
}
//初始化
this.keyNodeMap=new HashMap<K,Node<V>>();
this.NodeKeyMap=new HashMap<Node<V>,K>();
this.nodeList=new NodeDoubleLinkedList<V>();
this.capacity=capacity;
}
//对某个key值所对应的节点查询,移动节点
public V get(K key) {
if(this.keyNodeMap.containsKey(key)) {
//如果包含key
Node<V>res=this.keyNodeMap.get(key);
//将节点移动到末尾
this.nodeList.moveNodeToTail(res);
//返回要查询的值
return res.value;
}
//如果双向列表中无此节点,返回空
return null;
}
//设置节点的值,只要修改,移动节点
public void set(K key,V value) {
if(this.keyNodeMap.containsKey(key)) {
Node<V>node=this.keyNodeMap.get(key);
node.value=value;
this.nodeList.moveNodeToTail(node);
}else {
Node<V>newNode=new Node<V>(value);
this.keyNodeMap.put(key, newNode);
this.nodeList.addNode(newNode);
if(this.keyNodeMap.size()==this.capacity+1) {
this.removeMostUnsedCache();
}
}
}
//当内存不够时,移除最不经常使用的节点
private void removeMostUnsedCache() {
Node<V>removeNode=this.nodeList.removeHead();
K removeKey=this.NodeKeyMap.get(removeNode);
this.keyNodeMap.remove(removeKey);
}
}