Leetcode146-lru-cache
int capacity; int size; Map<Integer, ListNode> map = new HashMap<Integer, ListNode>(); ListNode head; ListNode last; class ListNode { int key; int value; ListNode prev; ListNode next; public ListNode(int key, int val) { this.key = key; this.value = val; prev = null; next = null; } public int getKey() { return key; } public void setKey(int key) { this.key = key; } public int getValue() { return value; } public void setValue(int value) { this.value = value; } } public LRUCache(int capacity) { this.capacity = capacity; } public int get(int key) { if (map.containsKey(key)) { return key; } return -1; } public void put(int key, int value) { if (map.containsKey(key)) { moveNode(key, value); } else { if (size < capacity) { insertNode(key, value); size++; } else { insertNode(key, value); last = last.next; } } } public void insertNode(int key, int value) { ListNode node; node = new ListNode(key, value); node.next = head; head = node; ListNode current = last; while (current.next != null) { current = current.next; } current.next = node; } public void moveNode(int key, int value) { ListNode node; node = new ListNode(key, value); node.next = head; head = node; while (node.next.getKey() != key && node.next.getKey() != last.getKey()) { node = node.next; } node.next = node.next.next; ListNode current = last; while (current.next.getKey() != key && current.next.getKey() != last.getKey()) { current = current.next; } current.next = current.next.next; }