Friday 30 August 2013

Stack example in c#.

Stack:-
It represents a last-in , first out collection of objects.
It is used when you want a last in ,first out access of items. When you add an item in the list, it is called pushing the item and when you remove it , it is called poping the item.

Properties Of  Stack Class:-
Count :- Gets the number of elements actually contained in the Stack.

Methods Of Stack Class :-
There are various methods in Stack class for ex. Add(), Peek(),Remove(),Pop(),Push() etc. I have explained all methods in below example of Stack .

Example:-
using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.Data;

namespace CollectionExample
{
    class Program
    {
////Stack Example-------------------------------------------------------------------------
            Console.WriteLine("-------------Stack table Example---------------");
            Stack st = new Stack();

            st.Push('S');
            st.Push('K');
            st.Push('M');
            st.Push('V');
            st.Push('A');

            st.Pop();

            Console.WriteLine("Content Of Stack:");
            foreach (char r in st)
            {
                Console.WriteLine(r);
            }
            st.Push('H');
            st.Push('N');

            Console.WriteLine("The last value in Stack:{0}", st.Peek());
            Console.WriteLine("Current Values in Stack:");
            foreach (char cv in st)
            {
                Console.WriteLine(cv + " ");
            }

            Console.ReadKey();
      }
   }
}

Output:-
-------------Stack table Example---------------
Content Of Stack:
V
M
K
S
The last value in Stack:N
Current Values in Stack:
N
H
V
M
K

S

No comments:

Post a Comment

Note: only a member of this blog may post a comment.