using System.Collections.Generic;
public static void Main()
var cache = new LRUCache<int, int>(3);
Console.WriteLine(cache.Get(4));
Console.WriteLine(cache.Get(3));
Console.WriteLine(cache.Get(2));
Console.WriteLine(cache.Get(1));
Console.WriteLine(cache.Get(1));
Console.WriteLine(cache.Get(2));
Console.WriteLine(cache.Get(3));
Console.WriteLine(cache.Get(4));
Console.WriteLine(cache.Get(5));
Console.WriteLine("Done");
public class LRUCache<K, V>
private readonly int _capacity;
private readonly Dictionary<K, LinkedListNode<(K Key, V Value)>> _cache;
private readonly LinkedList<(K Key, V Value)> _lruList;
public LRUCache(int capacity)
_cache = new Dictionary<K, LinkedListNode<(K Key, V Value)>>(capacity);
_lruList = new LinkedList<(K Key, V Value)>();
if (!_cache.TryGetValue(key, out var node))
public void Put(K key, V value)
if (_cache.TryGetValue(key, out var node))
node.Value = (key, value);
if (_cache.Count >= _capacity)
_cache.Remove(lru.Value.Key);
var newNode = new LinkedListNode<(K Key, V Value)>((key, value));
_lruList.AddFirst(newNode);