1.in C# if you use the System.Collections.Generic.LinkedLIst you have the built in Reverse() method but obviously that's not what the interviewer asked for;). the below is a implementation of a method which reverse your generic LinkedList (can take any type)
**by give it few tweaks it can also get a custom Linked List:
public static LinkedList ReverseLinkedList(LinkedList linkedList)
{
// ------------------------------------------------------------
// Create a new linked list and add all items of given
// linked list to the copy linked list in reverse order
// ------------------------------------------------------------
LinkedList copyList = new LinkedList();
// ------------------------------------------------------------
// Start from the latest node
// ------------------------------------------------------------
LinkedListNode start = linkedList.Last;
// ------------------------------------------------------------
// Traverse until the first node is found
// ------------------------------------------------------------
while (start != null)
{
// ------------------------------------------------------------
// Add item to the new link list
// ------------------------------------------------------------
copyList.AddLast(start.Value);
start = start.Previous;
}
return copyList;
}
2.
public class LeastRecentlyUsedCache
{
private readonly Dictionary entries;
private readonly int capacity;
private Node head;
private Node tail;
private class Node
{
public Node Next { get; set; }
public Node Previous { get; set; }
public TKey Key { get; set; }
public TValue Value { get; set; }
}
public LeastRecentlyUsedCache(int capacity = 16)
{
if (capacity ();
head = null;
}
public void Set(TKey key, TValue value)
{
Node entry;
if (!entries.TryGetValue(key, out entry))
{
entry = new Node { Key = key, Value = value };
if (entries.Count == capacity)
{
entries.Remove(tail.Key);
tail = tail.Previous;
if (tail != null) tail.Next = null;
}
entries.Add(key, entry);
}
entry.Value = value;
MoveToHead(entry);
if (tail == null) tail = head;
}
public bool TryGetValue(TKey key, out TValue value)
{
value = default(TValue);
Node entry;
if (!entries.TryGetValue(key, out entry)) return false;
MoveToHead(entry);
value = entry.Value;
return true;
}
private void MoveToHead(Node entry)
{
if (entry == head || entry == null) return;
var next = entry.Next;
var previous = entry.Previous;
if (next != null) next.Previous = entry.Previous;
if (previous != null) previous.Next = entry.Next;
entry.Previous = null;
entry.Next = head;
if (head != null) head.Previous = entry;
head = entry;
if (tail == entry) tail = previous;
}
}