实现代码
import java.util.HashMap;
import java.util.Map;
public class LRUCache {
static class ListNode{
int key;
int value;
ListNode pre;
ListNode next;
public ListNode(int key,int value){
this.key = key;
this.value = value;
}
public ListNode(){}
}
static Map<Integer,ListNode> nodeMap;
static int size;
static int capacity;
ListNode head;
ListNode tail;
public LRUCache(int capacity){
nodeMap = new HashMap<>();
this.capacity = capacity;
head = new ListNode();
tail = new ListNode();
head.next = tail;
tail.pre = head;
size = 0;
}
public int get(int key){
if(!nodeMap.containsKey(key)){
return -1;
}
ListNode node = nodeMap.get(key);
moveToHead(node);
return node.value;
}
public void put(int key, int value){
if(nodeMap.containsKey(key)){
ListNode node = nodeMap.get(key);
node.value = value;
moveToHead(node);
return;
}
if(size>=capacity){
ListNode node = tail.pre;
remove(node);
nodeMap.remove(node.key);
size--;
}
ListNode node = new ListNode(key,value);
addToHead(node);
nodeMap.put(key,node);
size++;
}
public void remove(ListNode node){
node.next.pre = node.pre;
node.pre.next = node.next;
}
public void addToHead(ListNode node){
node.next = head.next;
node.pre = head.next.pre;
head.next = node;
node.next.pre = node;
}
public void moveToHead(ListNode node){
remove(node);
addToHead(node);
}
}
测试代码
public void Test(){
LRUCache lruCache = new LRUCache(2);
lruCache.put(1,1);
lruCache.put(2,2);
System.out.println(lruCache.get(1));
lruCache.put(3,3);
System.out.println(lruCache.get(2));
lruCache.put(4,4);
System.out.println(lruCache.get(1));
System.out.println(lruCache.get(3));
System.out.println(lruCache.get(4));
}
输出
1
-1
-1
3
4