1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| @SuppressWarnings("FieldMayBeFinal") public class LRUCache<K,V>{ private Node<K,V> head=new Node<>(); private Node<K,V> tail=new Node<>(); private Map<K,Node<K,V>> map=new HashMap<>(); private int remain;
public LRUCache(int capacity){ remain=capacity; head.next=tail; tail.pre=head; }
public V get(K key){ Node<K,V> node = map.get(key); if(node==null){return null;} node.pre.next=node.next; node.next.pre=node.pre; node.next=head.next; node.pre=head; head.next.pre=node; head.next=node; return node.value; }
public V remove(K key){ Node<K,V> node = map.remove(key); if(node==null){return null;} node.pre.next=node.next; node.next.pre=node.pre; remain++; return node.value; }
public V put(K key, V value){ if(get(key)!=null){ Node<K,V> node = map.get(key); V oldVal=node.value; node.value=value; return oldVal; }else if(remain==0){ remove(tail.pre.key); } Node<K,V> node = new Node<>(key, value, head, head.next); head.next.pre=node; head.next=node; map.put(key,node); remain--; return null; }
private static class Node<K,V>{ private K key; private V value; private Node<K,V> pre,next;
private Node(){}
private Node(K key, V value, Node<K,V> pre, Node<K,V> next){ this.key=key; this.value=value; this.pre=pre; this.next=next; } } }
|