16.4 StacksA stack is a last-in, first-out (LIFO) collection, like a stack of dishes at a buffet table or a stack of coins on your desk. You add a dish on top, and that is the first dish you take off the stack.
The principal methods for adding to and removing from an instance of the Stack class are Push() and Pop(); Stack also offers a Peek() method, very much like Queue. Table 16-5 shows the most important methods and properties for Stack.
In Example 16-4, you rewrite Example 16-3 to use a Stack rather than a Queue. The logic is almost identical. The key difference is that a Stack is Last In, First Out, while a Queue is First In, First Out. Example 16-4. Using a Stackusing System; using System.Collections; namespace StackDemo { class Tester { public void Run() { Stack intStack = new Stack(); // populate the array for (int i = 0;i<8;i++) { intStack.Push(i*5); } // Display the Stack. Console.Write( "intStack values:\t" ); DisplayValues( intStack ); // Remove an element from the stack. Console.WriteLine( "\n(Pop)\t{0}", intStack.Pop() ); // Display the Stack. Console.Write( "intStack values:\t" ); DisplayValues( intStack ); // Remove another element from the stack. Console.WriteLine( "\n(Pop)\t{0}", intStack.Pop() ); // Display the Stack. Console.Write( "intStack values:\t" ); DisplayValues( intStack ); // View the first element in the // Stack but do not remove. Console.WriteLine( "\n(Peek) \t{0}", intStack.Peek() ); // Display the Stack. Console.Write( "intStack values:\t" ); DisplayValues( intStack ); } public static void DisplayValues( IEnumerable myCollection ) { foreach (object o in myCollection) { Console.WriteLine(o); } } [STAThread] static void Main() { Tester t = new Tester(); t.Run(); } } } Output: (Pop) 35 intStack values: 30 25 20 15 10 5 0 (Pop) 30 intStack values: 25 20 15 10 5 0 (Peek) 25 intStack values: 25 20 15 10 5 You start Example 16-4 by creating a Stack object called intStack: Stack intStack = new Stack(); Populate the stack with ints by calling the Push() method, which pushes the object onto the stack (i.e., adds it to the top of the stack); in this case, you push integers onto the stack. for (int i = 0;i<8;i++) { intStack.Push(i*5); } Remove an object from the stack by popping it off the stack with the Pop() method: Console.WriteLine( "\n(Pop)\t{0}", intStack.Pop() ); Just as you could peek at the object at the beginning of the queue without dequeing it, you can Peek() at the object on top of the stack without popping it: Console.WriteLine( "\n(Peek) \t{0}", intStack.Peek() ); |