7/26/2010

C# Collections (Stack)



Collections:
------------
Collection is defined as collection of values.
Collections are broadly classified into two type:
1.Collections that Does Not support random accessing.
Example:
         stack, queue
1.Collections that support random accessing.
Example:
         array, array list, hashtable

Include namespace System.Collections;

Collections that Does Not support random accessing:
1.Stack:
--------
      Stack follows the principle of First In Last Out(FILO) or Last In First Out(LIFO)
The following three operations performed on a stack.
1.Push():  Inserting an element into the stack.
1.Pop():   Deleting an element from the stack.
1.Peek(): Checking the top of the element of the stack.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace ConsoleApplication23
{
    class Program
    {
        static void Main(string[] args)
        {
            Stack s = new Stack(4);

            s.Push(45);
            s.Push(12);
            s.Push(6);
            s.Push(8);

            Console.WriteLine("No. of elements: " + s.Count);

            IEnumerator ie = s.GetEnumerator();

            Console.WriteLine("Stack Elements are: "+"\n"+"-------------");
            while (ie.MoveNext())
                Console.WriteLine(ie.Current);

            Console.WriteLine("Element deleted from the stack: " + s.Pop());

            Console.WriteLine("Elements in stack after pop( )");
            ie = s.GetEnumerator();
            while (ie.MoveNext())
                Console.WriteLine(ie.Current);

            Console.WriteLine("element on the stack top: " + s.Peek());
        }
    }
}

No comments:

Post a Comment