Tuesday, 5 May 2015

Stack

The stack is similar to a queue but the opposite, a stack is a First-in-Last-out or FiLo data structure. Think of a stack of cookies, you stack one on top of the other and when you go to eat your first cookie, it's the last one you put down. 



though a stack has several functions, the three main ones are:
  • Push: adds an item to the top of the stack
  • Pop: takes out the newest item from the top of stack
  • Peek: looks at the newest item on the top of the stack.

Now let's look at a demo


using System.Collections;

namespace pav.stackExample;
class Program
{
    static void Main(string[] args)
    {
        Stack s = new Stack();

        s.Push(1);
        s.Push("two");
        s.Push("Three");
        s.Push(4);
        s.Push(5.0);

        while (s.Count > 0)
            Console.WriteLine(s.Pop());
    }

}




one thing to keep in mind is that peek an empty stack will through an exception.