Wednesday, September 22, 2010

Working with stack

Working with stack:

Stack is another flexible collection class available in System.Collections namespace. Stack size increases dynamically as we add elements to the stack. In Stack the elements are organized in Last In First Out (LIFO) format. Stack has general Push ( ) and Pop ( ) methods by using which we can push the elements into the stack and we can pop (retrieve) the elements from the stack.

Common Methods used in Stack

Push():
Is used to add elements to the stack.
Insert elements into stack:
Stack Products = new Stack();
Products.Push("FM Transmitter");
Products.Push("DJ Cable");
Products.Push("Power Adapter");
Add an array to stack:
string [ ]products = new string[3]{ "Transmitter", "DJ Cable ", "Power Adapter " };
Stack Products = new Stack();
Products.Push(products);

Pop():
Removes and returns the element at the top of the stack. The following code shows the functionality of pop().
   Stack Products = new Stack();
  Products.Push("FM Transmitter");
  Products.Push("DJ Cable");
  Products.Push("Power Adapter");
  Console.WriteLine("Before pop()");
  foreach (string s in Products)
     {
           Console.WriteLine(s);
     }
  Console.WriteLine("===============");
  Console.WriteLine("Pop out element:{0}", Products.Pop());
  Console.WriteLine("=================\n After Pop()");
  foreach (string s in Products)
     {
          Console.WriteLine(s);
     }

Peek:
Is used to return the top element from the stack without removing it.
Stack Products = new Stack();
Products.Push("FM Transmitter");
Products.Push("DJ Cable");
Products.Push("Power Adapter");    
Console.WriteLine("{0}", Products.Peek());

Contains():
Returns a boolean value which is used to determine whether an element is in the list.
Stack Products = new Stack();
Products.Push("FM Transmitter");
Products.Push("DJ Cable");
Products.Push("Power Adapter");    
Console.WriteLine("{0}",Products.Contains("DJ Cable"));

CopyTo():
Is used to copies entire elements in the stack to an existing one dimensional array.
string[ ] products = new string[ 3 ];
Stack Products = new Stack();
Products.Push("FM Transmitter");
Products.Push("DJ Cable");
Products.Push("Power Adapter");
Products.CopyTo(products, 0);
foreach (string s in products)
    {
       Console.WriteLine("{0}", s);
    }

Next:
Working with Queue.

Furhter Reading:

No comments:

Post a Comment