Skip to content

Instantly share code, notes, and snippets.

@michael-duren
Created December 10, 2025 00:13
Show Gist options
  • Select an option

  • Save michael-duren/bb028b1ac4f066925b15d0af2b52e3e0 to your computer and use it in GitHub Desktop.

Select an option

Save michael-duren/bb028b1ac4f066925b15d0af2b52e3e0 to your computer and use it in GitHub Desktop.
public class LRUCache(int capacity)
{
public class ListNode(int key, int value)
{
public readonly int Key = key;
public int Value = value;
public ListNode Prev;
public ListNode Next;
}
private readonly Dictionary<int, ListNode> _cache = [];
private ListNode _head;
private ListNode _tail;
private readonly int _capacity = capacity;
public int Get(int key)
{
if (!_cache.TryGetValue(key, out ListNode listNode))
{
return -1;
}
if (listNode == _head)
return listNode.Value;
MoveToHead(listNode);
return listNode.Value;
}
public void Put(int key, int value)
{
if (_cache.TryGetValue(key, out ListNode node))
{
node.Value = value;
MoveToHead(node);
return;
}
var listNode = new ListNode(key, value);
_cache[key] = listNode;
AddToFront(listNode);
if (_cache.Count > _capacity)
{
_cache.Remove(_tail.Key);
RemoveNode(_tail);
}
MoveToHead(listNode);
}
private void MoveToHead(ListNode listNode)
{
if (listNode is null)
return;
RemoveNode(listNode);
AddToFront(listNode);
}
private void RemoveNode(ListNode node)
{
if (node.Prev != null)
node.Prev.Next = node.Next;
else
_head = _head.Next;
if (node.Next != null)
node.Next.Prev = node.Prev;
else
_tail = _tail.Prev;
}
private void AddToFront(ListNode node)
{
node.Prev = null;
node.Next = _head;
if (_head is not null)
_head.Prev = node;
_head = node;
_tail ??= node;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment