I am new with using Generics and trying to implement a LRU cache using Generic Circular doubly linked list in C#. I am having couple of issues. Please help me out
1) In my LRUCache constructor am doing this
head = new Node<T>(default(T), default(T));
which is not right, I want to initialize my head with some default keyvalue pair(-1,-1) data instead of Types default values.
2)In my get I am checking node is null based on the key and returning default(T). But I want to return null itself.
Here is my code
public class Node<T>
{
public KeyValuePair<T, T> KeyValue { get; set; }
public Node<T> Next { get; set; }
public Node<T> Previous { get; set; }
public Node(T key, T value)
{
this.KeyValue = new KeyValuePair<T, T>(key, value);
Next = null;
Previous = null;
}
}
public class LRUCache<T>
{
private readonly int capacity;
private int count;
private readonly Node<T> head;
private readonly Dictionary<T, Node<T>> myDictionary;
public LRUCache(int capacity)
{
head = new Node<T>(default(T), default(T));
head.Next = head;
head.Previous = head;
this.capacity = capacity;
myDictionary = new Dictionary<T, Node<T>>();
}
public void set(T key, T value)
{
Node<T> node;
myDictionary.TryGetValue(key, out node);
if (node == null)
{
if (this.count == this.capacity)
{
// remove the last element
myDictionary.Remove(head.Previous.KeyValue.Key);
head.Previous = head.Previous.Previous;
head.Previous.Next = head;
count--;
}
// create new node and add to dictionary
var newNode = new Node<T>(key, value);
myDictionary[key] = newNode;
this.InsertAfterTheHead(newNode);
// increase count
count++;
}
else
{
node.KeyValue = new KeyValuePair<T, T>(key, value);
this.MoveToFirstElementAfterHead(node);
}
}
public T get(T key)
{
Node<T> node;
myDictionary.TryGetValue(key, out node);
if (node == null)
{
return default(T);
}
this.MoveItToFirstElementAfterHead(node);
return node.KeyValue.Value;
}
}