public void Add(int key, int value) { // just need to update value and move it to the top if (map.ContainsKey(key)) { LRUNode node = map[key]; doubleLinkedList.RemoveNode(node); node.Value = value; doubleLinkedList.AddToTop(node); } else { // if cache is full, then remove the least recently used node if (count == capacity) { LRUNode lru = doubleLinkedList.RemoveLRUNode(); // remove the node map.Remove(lru.Key); // the move the key out of the dictionary count--; } // add a new node on top LRUNode node = new LRUNode(key, value); doubleLinkedList.AddToTop(node); map[key] = node; count++; } }
public LRUNode RemoveLRUNode() { LRUNode target = Tail.Previous; RemoveNode(target); return(target); }
public void RemoveNode(LRUNode node) { node.Previous.Next = node.Next; node.Next.Previous = node.Previous; node.Next = null; node.Previous = null; }
public void AddToTop(LRUNode node) { node.Next = Head.Next; Head.Next.Previous = node; node.Previous = Head; Head.Next = node; }
public LRUDoubleLinkedList() { Head = new LRUNode(); Tail = new LRUNode(); Head.Next = Tail; Tail.Previous = Head; }
// each time when access the node, we move it to the top public int Get(int key) { if (!map.ContainsKey(key)) { return(-1); } LRUNode node = map[key]; doubleLinkedList.RemoveNode(node); // Remove node out of the list doubleLinkedList.AddToTop(node); // Add back it on the top return(node.Value); }