[LeetCode]LRU Cache
public class LRUCache { HashMap<Integer, ListNode> map = new HashMap<Integer, ListNode>(); ListNode start; ListNode end; int capacity; int cur_size; public LRUCache(int capacity) { this.capacity = capacity; cur_size = 0; start = new ListNode(0); end = new ListNode(0); start.next = end; end.pre = start; } public int get(int key) { if (!map.containsKey(key)) { return -1; } ListNode node = map.get(key); delete(node); insert(node); return node.val; } public void set(int key, int value) { if (map.containsKey(key)) { get(key); map.get(key).val = value; return; } if (cur_size < capacity) { cur_size ++; } else { map.remove(start.next.key); start.next = start.next.next; start.next.pre = start; } ListNode node = new ListNode(value); node.key = key; map.put(key, node); insert(node); } private void delete(ListNode node) { node.pre.next = node.next; node.next.pre = node.pre; } private void insert(ListNode node) { end.pre.next = node; node.pre = end.pre; node.next = end; end.pre = node; } class ListNode { int val; int key; ListNode pre; ListNode next; ListNode(int val) { this.val = val; } } }