Creating Stacks


Stacks are the opposite of queues. A stack is a list in which the first item in is the last item to be read.

To create a stack, add items to it, and remove items from it:

  1. Type System.Collections.Stack .

  2. Type the name of the stack variable that is to store the stack object, for example: msgs .

  3. Type = .

  4. Type new System.Collections.Stack() .

  5. Type a semicolon ; .

  6. Type msgs.Push("Task1"); where "Task1" is the item to add to the stack.

  7. Type msgs.Pop(); to extract the most recent addition from the stack ( Figure 9.56 ).

    Figure 9.56 With a stack you Push and Pop. Push puts the element on top of the stack, Pop removes the top element (first inlast out).
     void Task() {    System.Collections.Stack q1 = new    System.Collections.Stack();    q1.  Push  ("Task1");    q1.  Push  ("Task2");    q1.  Push  ("Task3");    string s1 = (string)q1.  Pop  (); //Task3    string s2 = (string)q1.  Pop  (); //Task2    string s3 = (string)q1.  Pop()  ; //Task1 } 

graphics/tick.gif Tip

  • As with queues, you can enumerate through the items in the stack without removing them using the foreach function ( Figure 9.57 ).

    Figure 9.57 Using foreach you can peek through the elements of the stack without removing them.
     void Task() {    System.Collections.Stack q1 = new    System.Collections.Stack();    q1.Push("Task1");    q1.Push("Task2");    q1.Push("Task3");  foreach (string task in q1)   {   Response.Write(task + ",");   //Prints: Task3, Task2, Task1,   }  } 



C#
C# & VB.NET Conversion Pocket Reference
ISBN: 0596003196
EAN: 2147483647
Year: 2003
Pages: 198
Authors: Jose Mojica

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net