Stack
As most readers know, a stack is a first-in, last-out list. To visualize a stack, imagine a stack of plates on a table. The first plate put down is the last one to be picked up. The stack is one of the most important data structures in computing. It is frequently used in system software, compilers, and AI-based backtracking routines, to name just a few examples.
The collection class that supports a stack is called Stack. It implements the ICollection, IEnumerable, and ICloneable interfaces. Stack is a dynamic collection that grows as needed to accommodate the elements it must store.
Stack defines the following constructors:
public Stack( ) public Stack(int initialCapacity) public Stack(ICollection col)
In addition to the methods defined by the interfaces that it implements, Stack defines the methods shown in following Table. In general, here is how you use Stack. To put an object on the top of the stack, call Push( ). To remove and return the top element, call Pop( ). You can use Peek( ) to return, but not remove, the top object. An InvalidOperationException is thrown if you call Pop( ) or Peek( ) when the invoking stack is empty.
Method | Description |
---|---|
public virtual void Clear( ) | Sets Count to zero, which effectively clears the stack. |
public virtual bool Contains(object obj) | Returns true if obj is on the invoking stack. If obj is not found, false is returned. |
public virtual object Peek( ) | Returns the element on the top of the stack, but does not remove it. |
public virtual object Pop( ) | Returns the element on the top of the stack, removing it in the process. |
public virtual void Push(object obj) | Pushes obj onto the stack. |
public static Stack Synchronized(Stack stack) | Returns a synchronized version of the Stack passed in stack. |
public virtual object[ ] ToArray( ) | Returns an array that contains copies of the elements of the invoking stack. |
Example
using System; using System.IO; using System.Collections; namespace ConsoleApplication1 { class Program { static void ShowPush(Stack st, int a) { st.Push(a); Console.WriteLine("Push(" + a + ")"); Console.Write("stack: "); foreach (int i in st) Console.Write(i + " "); Console.WriteLine(); } static void ShowPop(Stack st) { Console.Write("Pop -> "); int a = (int)st.Pop(); Console.WriteLine(a); Console.Write("stack: "); foreach (int i in st) Console.Write(i + " "); Console.WriteLine(); } static void Main() { Stack st = new Stack(); foreach (int i in st) Console.Write(i + " "); Console.WriteLine(); ShowPush(st, 22); ShowPush(st, 65); ShowPush(st, 91); ShowPop(st); ShowPop(st); ShowPop(st); try { ShowPop(st); } catch (InvalidOperationException) { Console.WriteLine("Stack empty."); } Console.Read(); } } }