15.5 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 it 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. The most important methods and properties for Stack are shown in Table 15-5. Table 15-5. Stack members
In Example 15-5, you rewrite Example 15-4 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 15-5. Using a StackOption Strict On Imports System Namespace StackDemo Class Tester Public Sub Run( ) Dim intStack As New Stack( ) ' populate the stack Dim i As Integer For i = 0 To 7 intStack.Push((i * 5)) Next i ' Display the Stack. Console.WriteLine("intStack values:") DisplayValues(intStack) ' Remove an element from the stack. Console.WriteLine("(Pop){0}", intStack.Pop( )) ' Display the Stack. Console.WriteLine("intStack values:") DisplayValues(intStack) ' Remove another element from the stack. Console.WriteLine("(Pop){0}", intStack.Pop( )) ' Display the Stack. Console.WriteLine("intStack values:") DisplayValues(intStack) ' View the first element in the ' Stack but do not remove. Console.WriteLine("(Peek) {0}", intStack.Peek( )) ' Display the Stack. Console.WriteLine("intStack values:") DisplayValues(intStack) End Sub 'Run Public Shared Sub DisplayValues(ByVal myCollection As IEnumerable) Dim o As Object For Each o In myCollection Console.WriteLine(o) Next o End Sub 'DisplayValues Shared Sub Main( ) Dim t As New Tester( ) t.Run( ) End Sub 'Main End Class 'Tester End Namespace 'StackDemo Output: intStack values: 35 30 25 20 15 10 5 0 (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 15-5 by creating a Stack object called intStack: Dim intStack As New Stack( ) You populate the stack with integers by calling the Push( ) method, which pushes each integer object onto the stack (i.e., adds it to the top of the Stack): For i = 0 To 7 intStack.Push((i * 5)) Next i You remove an object from the stack by popping it off the stack with the Pop( ) method: Console.WriteLine("(Pop){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("(Peek) {0}", intStack.Peek( )) |