Stack Type
This page was last reviewed on May 29, 2024.
Dot Net Perls
Stack. A Stack adds elements to its top. Elements are pushed to the top, and then popped from the top. The last element added to the Stack is the first element removed from the Stack.
Stack info. We see how to loop over a VB.NET Stack, push and pop elements, and also peek and count. The stack can be used for parsing text.
Example. We Push elements to the top of a Stack. Then, we use the For-Each loop to display the Stack. The most recently added element (1000) is at the top of the Stack.
Module Module1 Sub Main() Dim stack As Stack(Of Integer) = New Stack(Of Integer) stack.Push(10) stack.Push(100) stack.Push(1000) ' Display stack elements. For Each value As Integer In stack Console.WriteLine(value) Next End Sub End Module
1000 100 10
Example 2. We use the Pop and Peek functions. With Pop, you take the top element off of the Stack and it is stored in the return value. It is no longer is part the Stack.
Info With Peek, you take the top element and copy it to the return value, but it is not removed.
Tip To avoid exceptions with an empty stack, use the Count property and test it against zero.
Module Module1 Sub Main() Dim stack As Stack(Of Integer) = New Stack(Of Integer) stack.Push(10) stack.Push(100) stack.Push(1000) ' Test Pop. Dim value As Integer = stack.Pop Console.WriteLine("Element popped: {0}", value) ' Test Peek. value = stack.Peek Console.WriteLine("Element peeked: {0}", value) End Sub End Module
Element popped: 1000 Element peeked: 100
Example 3. We show how to copy an array into a new Stack. Please note that the types of the two collections must match. The array of Strings must be copied to a Stack of Strings.
Next We use the Contains function, which works in much the same way as the List Contains function. It returns True or False.
Module Module1 Sub Main() Dim array(2) As String array(0) = "dot" array(1) = "net" array(2) = "perls" ' Copy array to a new stack. Dim stack As Stack(Of String) = New Stack(Of String)(array) ' Use Contains. Console.WriteLine(stack.Contains("net")) Console.WriteLine(stack.Contains("not")) End Sub End Module
True False
The Stack collection can be used to implement certain parsers that track nesting levels, such as HTML parsers. As each nested element is encountered, a new element is added to the Stack.
Final note. Stacks are useful in any system where the most recently added element is the most urgent. The VB.NET Stack type is used to implement a variety of important algorithms.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 29, 2024 (edit).
© 2007-2024 Sam Allen.