package com.heu.wsq.leetcode.mylinkedlist;
import java.util.HashMap;
import java.util.Map;
public class LRUCache {
class DLinkedNode{
int key;
int value;
DLinkedNode prev;
DLinkedNode next;
public DLinkedNode(){}
public DLinkedNode(int key, int value){
this.key = key;
this.value = value;
}
}
private Map<Integer, DLinkedNode> cache;
private int capacity;
private int size;
private DLinkedNode head, tail;
public LRUCache(int capacity){
this.capacity = capacity;
this.size = 0;
this.cache = new HashMap<>();
this.head = new DLinkedNode();
this.tail = new DLinkedNode();
this.head.next = this.tail;
this.tail.next = this.head;
}
public int get(int key) {
DLinkedNode node = this.cache.get(key);
if(node == null){
return -1;
}
moveToHead(node);
return node.value;
}
public void put(int key, int value) {
DLinkedNode node = cache.get(key);
if(node == null){
DLinkedNode newNode = new DLinkedNode(key, value);
this.cache.put(key, newNode);
addToHead(newNode);
++this.size;
if(this.size > this.capacity){
DLinkedNode tailNode = rmTailNode();
this.cache.remove(tailNode.key);
this.size--;
}
}else{
node.value = value;
moveToHead(node);
}
}
private void removeNode(DLinkedNode node){
node.prev.next = node.next;
node.next.prev = node.prev;
}
private void addToHead(DLinkedNode node){
node.next = this.head.next;
node.next.prev = node;
node.prev = this.head;
this.head.next = node;
}
private DLinkedNode rmTailNode(){
DLinkedNode node = this.tail.prev;
removeNode(node);
return node;
}
private void moveToHead(DLinkedNode node){
removeNode(node);
addToHead(node);
}
}