public void Put(int key, int value) { if (cache.ContainsKey(key)) { // update the value. cache[key].value = value; moveToHead(cache[key]); } else { DLinkedNode newNode = new DLinkedNode(); newNode.key = key; newNode.value = value; cache.Add(key, newNode); addNode(newNode); ++size; if (size > capacity) { // pop the tail DLinkedNode tail = popTail(); cache.Remove(tail.key); --size; } } }
private DLinkedNode popTail() { //Pop the current tail. DLinkedNode res = tail.prev; removeNode(res); return(res); }
private void removeNode(DLinkedNode node) { // Remove an existing node from the linked list. DLinkedNode prev = node.prev; DLinkedNode next = node.next; prev.next = next; next.prev = prev; }
private void addNode(DLinkedNode node) { //Always add the new node right after head. node.prev = head; node.next = head.next; head.next.prev = node; head.next = node; }
public int Get(int key) { if (!cache.ContainsKey(key)) { return(-1); } DLinkedNode node = cache[key]; moveToHead(node); return(node.value); }
public LRUCache(int capacity) { this.size = 0; this.capacity = capacity; head = new DLinkedNode(); // head.prev = null; tail = new DLinkedNode(); // tail.next = null; head.next = tail; tail.prev = head; }
private void moveToHead(DLinkedNode node) { // Move certain node in between to the head. removeNode(node); addNode(node); }