Introduction
The Stack class implements a Last In First Out data structure. The objects are stored in such a manner that the object added last is placed at the top of the stack.
Stack Interfaces
The Stack class implements the three major collection interfaces. They are ICollection, IEnumerable and ICloneable.
Important Stack methods
Push - Used to add a new object at the top of the stack Pop - Removes and returns the object at the top of the stack. Peek – Returns the object at the top of the stack, but does not remove the item. Clear – Deletes all the objects from the stack. Contains – Returns true if a specified object is found in the stack else returns false.
The Stack stores the objects in an array as like the Queue.
An example is given below
{ static void Main(string[] args) { Stack vegStack = new Stack();
vegStack.Push("Raddish"); vegStack.Push("Cabbage"); vegStack.Push("Carrot"); vegStack.Push("Brinjal"); vegStack.Push("Onion");
Console.WriteLine("Contents of Vegetable Stack..."); foreach(string veg in vegStack) { Console.WriteLine(veg); }
while(vegStack.Count > 0) { string veg = (string) vegStack.Pop(); Console.WriteLine("Popping {0}", veg ); } } }
When the code is executed, the output is as follows
Contents of Vegetable Stack... Raddish Cabbage Carrot Brinjal Onion Popping Raddish Popping Cabbage Popping Carrot Popping Brinjal Popping Onion
Summary
The .NET framework also includes a wide variety of collection types, including types that implements Queue and HashTable.
|
| Author: venkateshwar rao gundlapally 22 Sep 2005 | Member Level: Bronze Points : 0 |
Hi, You done good job, but result shown is in reverse order. Pop always returns an item which was pushed last. Here Onion is the last item to push, so first outcome is Onion, etc.,
|
| Author: meenakshi 29 Mar 2007 | Member Level: Silver Points : 0 |
The output is not correct.Try to debug!!!
|