public class LRU {
final static int MAXSIZE = 5;
public static void main(String[] args) {
// 用来存储缓存
HashMap cache = new HashMap<>();
Node head = new Node<>(0,"0");
myPut(cache,new Node(1,"a") , head);
myPut(cache,new Node(2,"b"), head);
myPut(cache,new Node(3,"c"), head);
myPut(cache,new Node(4,"d"), head);
myPut(cache,new Node(5,"e"), head);
myPut(cache,new Node(6,"f"), head);
myPut(cache,new Node(7,"g"), head);
System.out.println(myGet(cache, head, 4));
}
public static void myPut(Map cache , Node node , Node head){
Node p = head;
// 先把node添加到队头
node.next = p.next;
p.next = node;
// 缓存数量达到上限
if (cache.size() >= MAXSIZE){
// 遍历到队尾删除最后一个元素
for (int i = 0 ; i < MAXSIZE ; i++){
p = p.next;
}
// 删除缓存中的元素
cache.remove(node.key);
p.next = null;
}
// node添加到缓存中
cache.put(node.key,node.value);
Node temp = head.next;
while (temp != null){
System.out.print(temp.value+"->");
temp = temp.next;
}
System.out.println();
}
public static String myGet(Map cache , Node head , Integer key){
Node p = head;
String res = null;
// key存在
if (cache.containsKey(key)){
// 获取value
res = cache.get(key);
// 找到p
while (p.next.key != key){
p = p.next;
}
// 被获取的元素放入队头
Node temp = p.next;
p.next = temp.next;
temp.next = head.next;
head.next = temp;
}
Node temp = head.next;
while (temp != null){
System.out.print(temp.value+"->");
temp = temp.next;
}
System.out.println();
return res;
}
}
class Node{
K key;
V value;
Node next;
public Node(K key, V value) {
this.key = key;
this.value = value;
this.next = null;
}
}