import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
public class SolveQ8 {
public static void main(String[] args) {
LRUCache chche = new LRUCache(3);
chche.put(1,11);
chche.put(2,22);
chche.put(3,33);
chche.put(1,111);
System.err.println(chche.get(1));
}
public static Object LRU_LINKEDHASHMAP(Object key){
LinkedHashMap<Object, Object> objectObjectLinkedHashMap = new LinkedHashMap<Object, Object>(2);
objectObjectLinkedHashMap.put(1,"zhangsan");
objectObjectLinkedHashMap.put(2,"lisi");
objectObjectLinkedHashMap.put(3,"wangwu");
return objectObjectLinkedHashMap.get(key);
}
}
class LRUCache{
Map<Integer,Node> map = new HashMap<>(8);
DoubleList doubleList;
int maxSize;
public LRUCache(int capacity){
doubleList = new DoubleList();
maxSize = capacity;
}
public int get(int key){
int val;
if(!map.containsKey(key)){
return -1;
}
val = map.get(key).value;
Node team = map.get(key);
doubleList.deleteNode(team);
doubleList.add(team);
return val;
}
public void put(int key,int value){
if(map.containsKey(key)){
Node deleteNode = map.get(key);
doubleList.deleteNode(deleteNode);
}
if(maxSize == doubleList.length){
Node first = doubleList.head.next;
map.remove(first.key);
doubleList.deleteFirst();
}
Node node = new Node(key,value);
map.put(key,node);
doubleList.add(node);
}
class Node {
int key;
int value;
Node pre;
Node next;
public Node(){}
public Node(int key,int value){
this.key = key;
this.value = value;
}
}
class DoubleList{
private Node head;
private Node tail;
private int length;
public DoubleList(){
head = new Node(-1,-1);
tail = head;
length = 0;
}
void add(Node teamNode){
tail.next = teamNode;
teamNode.pre = tail;
tail = teamNode;
length++;
}
void deleteFirst(){
if(head.next == null)
return;
if(head.next == tail)
head = tail;
head.next = head.next.next;
if(head.next != null)
head.next.pre = head;
length--;
}
void deleteNode(Node teamNode){
teamNode.pre.next = teamNode.next;
if(teamNode.next != null)
teamNode.next.pre = teamNode.pre;
if(teamNode == tail)
tail = tail.pre;
teamNode.pre = null;
teamNode.next = null;
length--;
}
}
}
|