MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / LRUCache

Class LRUCache

csharp/Linked Lists/LRUCache.cs:22–93  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

20}
21
22public class LRUCache
23{
24 private readonly int _capacity;
25 private readonly Dictionary<int, DoublyLinkedListNode> _hashMap;
26 private readonly DoublyLinkedListNode _head;
27 private readonly DoublyLinkedListNode _tail;
28
29 public LRUCache(int capacity)
30 {
31 _capacity = capacity;
32
33 // A hash map that maps keys to nodes
34 _hashMap = new Dictionary<int, DoublyLinkedListNode>();
35
36 // Initialize the head and tail dummy nodes and connect them to
37 // each other to establish a basic two-node doubly linked list.
38 _head = new DoublyLinkedListNode(-1, -1);
39 _tail = new DoublyLinkedListNode(-1, -1);
40 _head.Next = _tail;
41 _tail.Prev = _head;
42 }
43
44 public int Get(int key)
45 {
46 if (!_hashMap.ContainsKey(key))
47 return -1;
48
49 // To make this key the most recently used, remove its node and
50 // re-add it to the tail of the linked list.
51 removeNode(_hashMap[key]);
52 addToTail(_hashMap[key]);
53
54 return _hashMap[key].Val;
55 }
56
57 public void Put(int key, int value)
58 {
59 // If a node with this key already exists, remove it from the linked list.
60 if (_hashMap.ContainsKey(key))
61 removeNode(_hashMap[key]);
62
63 DoublyLinkedListNode node = new DoublyLinkedListNode(key, value);
64 _hashMap[key] = node;
65
66 // Remove the least recently used node from the cache if adding
67 // this new node will result in an overflow.
68 if (_hashMap.Count > _capacity)
69 {
70 _hashMap.Remove(_head.Next.Key);
71 removeNode(_head.Next);
72 }
73
74 addToTail(node);
75 }
76
77 private void addToTail(DoublyLinkedListNode node)
78 {
79 DoublyLinkedListNode prevNode = _tail.Prev;

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected