Implementing Stack using Linked List - C#. Please add error-handling in real-world usage.


//Sample linked list Node implementation
public class Node
{
public object Data { get; set; }

public Node Next { get; set; }

public Node(object d)
{
this.Data = d;
}

public void AddNextNode(object d)
{
Node node = this;
Node newNode = new Node(d);
while (node.Next != null)
{
node = node.Next;
}
node.Next = newNode;
}
}
//Stack implementation using linked list with standard operations - Push, Pop, Clear
public class Stack
{
private Node _top = null;

public int Count
{
get;
private set;
}

public Stack()
{
this.Count = 0;
}

public void Push(object obj)
{
Node newNode = new Node(obj);
if (_top == null)
_top = newNode;
else
{
Node temp = _top;
_top = newNode;
_top.Next = temp;
}
Count++;
}

public object Pop()
{
Node objToPop = _top;
_top = _top.Next;
Count--;
return objToPop.Data;
}

public void Clear()
{
_top = null;
Count = 0;
}

}

Read more: http://feeds.dzone.com/~r/dzone/snippets/~3/4q1CrHCQJSo/12605