I commented on a question and blindly asserted that a Stack based on a linked list was rather elegant (see here)
I haven't ever written a Stack in C# so I thought I should back up my claim:
public class Stack<T> : IEnumerable<T>
{
protected class StorageNode
{
public T Value { get; set; }
public StorageNode Next { get; set; }
public StorageNode(T value)
{
Value = value;
}
}
public int Count { get; private set; }
private StorageNode head;
public void Push(T value)
{
var newNode = new StorageNode(value);
if (head != null)
{
newNode.Next = head;
}
head = newNode;
++Count;
}
public T Pop()
{
if (head == null)
{
throw new InvalidOperationException("Cannot pop an empty stack");
}
var result = head.Value;
head = head.Next;
--Count;
return result;
}
public IEnumerator<T> GetEnumerator()
{
var current = head;
while (current != null)
{
yield return current.Value;
current = current.Next;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
I didn't use the .Net LinkedList because I thought it was a bit overkill for a singly linked list...
Is there anything I can improve in my code?