public void Add(string hashID, string redirectUrl) { if (string.IsNullOrEmpty(hashID) || string.IsNullOrWhiteSpace(hashID)) { throw new ArgumentException("HashID cannot be null, empty or white spaces"); } if (string.IsNullOrEmpty(redirectUrl) || string.IsNullOrWhiteSpace(redirectUrl)) { throw new ArgumentException("Redirect URL cannot be null, empty or white spaces"); } if (nodeMap.ContainsKey(hashID)) { // Update existing node's value. LRUNode existingNode = nodeMap[hashID]; doubledLinkedList.RemoveNode(existingNode); existingNode.RedirectUrl = redirectUrl; doubledLinkedList.AddToFront(existingNode); } else { // LRU cache is full, removing least recently used node // from map and list. if (count == capacity) { LRUNode removedNode = doubledLinkedList.RemoveLRUNode(); nodeMap.Remove(removedNode.HashID); count--; } LRUNode newNode = new LRUNode(hashID, redirectUrl); doubledLinkedList.AddToFront(newNode); nodeMap[hashID] = newNode; count++; } }
public LRUDoubleLinkedList() { Head = new LRUNode(); Tail = new LRUNode(); Head.Next = Tail; Tail.Previous = Head; }
public LRUNode RemoveLRUNode() { LRUNode target = Tail.Previous; if (target == null) { throw new InvalidOperationException("Cannot remove node when list is empty."); } RemoveNode(target); return(target); }
public void RemoveNode(LRUNode node) { if (node == null) { throw new ArgumentException("Cannot remove null node."); } node.Previous.Next = node.Next; node.Next.Previous = node.Previous; node.Next = null; node.Previous = null; }
public void AddToFront(LRUNode node) { if (node == null) { throw new ArgumentException("New node cannot be null."); } node.Next = Head.Next; Head.Next.Previous = node; node.Previous = Head; Head.Next = node; }
public string Get(string hashID) { if (!nodeMap.ContainsKey(hashID)) { return(null); } if (string.IsNullOrEmpty(hashID) || string.IsNullOrWhiteSpace(hashID)) { throw new ArgumentException("HashID cannot be null, empty or white spaces"); } LRUNode existingNode = nodeMap[hashID]; // Move node to front of list when read. doubledLinkedList.RemoveNode(existingNode); doubledLinkedList.AddToFront(existingNode); return(existingNode.RedirectUrl); }