# 数据结构与算法 -- 内存置换算法LRU

import java.util.HashMap;

public class LRU {
public static class Node<K, V>{
public K key;
public V value;
public Node<K, V> last;
public Node<K, V> next;

public Node(K key, V value){
this.key = key;
this.value = value;
}
}

private Node<K, V> tail;
this.tail = null;
}

if (newNode == null) {
return;
}
this.tail = newNode;
}else {
this.tail.next = newNode;
newNode.last = this.tail;
this.tail = newNode;
}
}

public void moveToTail(Node<K, V> node){
if (this.tail == node){
return;
}
}else{
node.last.next = node.next;
node.next.last = node.last;
}
node.next = null;
node.last = this.tail;
this.tail.next = node;
this.tail = node;
}

return null;
}
this.tail= null;
}else {
res.next = null;
}
return res;
}

}

public static class MyCache<K, V>{
private HashMap<K, Node<K, V>> keyNodeMap;
private int capacity;
public MyCache(int capacity){
if (capacity < 1){
throw new RuntimeException("should more than 0");
}
this.capacity = capacity;
this.keyNodeMap = new HashMap<K, Node<K, V>>();
}

public V get(K key){
if (keyNodeMap.containsKey(key)){
Node<K, V> res = keyNodeMap.get(key);
this.nodeList.moveToTail(res);
return res.value;
}
return null;
}

public void set(K key, V value) {
if (this.keyNodeMap.containsKey(key)){
Node<K, V> res = this.keyNodeMap.get(key);
res.value = value;
this.nodeList.moveToTail(res);
}else{
Node<K, V> newNode = new Node<K, V>(key, value);
this.keyNodeMap.put(key, newNode);
if (this.keyNodeMap.size() == this.capacity + 1){
removeMostUnUsedCache();
}
}
}
public void removeMostUnUsedCache(){
this.keyNodeMap.remove(key);
}
}

public static void main(String[] args) {
MyCache<String, Integer> testCache = new MyCache<>(3);
testCache.set("a", 1);
System.out.println(testCache.get("a"));
}
}



06-12 47
08-23 398
05-02 3898
11-15 107
12-30
11-18 133
02-07 2138
10-06 149
01-30 8269