4.2.3.1 - Stacks and their operations (VB.NET)

4.2.3.1 - Stacks and their operations (VB.NET)

Maintain a stack in VB.NET, distinguish push, pop and peek, and protect empty and full boundaries. This route uses written code with no Run: incomplete: runnable support pending.

LIFO and stack state

A stack restricts insertion and removal to one end called the top.

Stack

A last-in, first-out collection: the most recently added remaining item is the next one removed.

An undo system stacks actions: undo reverses the latest action before an earlier one. Subroutine calls also use stack-like behaviour: a nested call finishes before control returns to its caller. These uses depend on order, not on the stack being drawn vertically.

For an array of capacity 4, choose top = -1 to represent no live items. With this convention the live cells are indices 0 through top, and the number of items is top + 1. Push increases top then stores the item; pop reads the current top then decreases it. A different convention can use the next free position, but formulas must change consistently.

After pushing Red, Blue and Green, top = 2 and Green is removed first. The array cell may still contain Green after a pop; it is no longer live when top has decreased. Do not mistake retained bytes for an extra stack item.

Push, pop and peek

Push changes the collection, pop returns and removes an item, and peek returns an item without removing it.

The complete library example prints B, 2, B and 1: the first B is only inspected, while the second B is removed.

VB.NET
Option Strict On
Imports System
Imports System.Collections.Generic
Module Program
    Sub Main()
        Dim history As New Stack(Of String)()
        history.Push("A")
        history.Push("B")
        Console.WriteLine(history.Peek())
        Console.WriteLine(history.Count)
        Console.WriteLine(history.Pop())
        Console.WriteLine(history.Count)
    End Sub
End Module

To expose the maintenance rules, a bounded array stack could use these members inside a module. TryPop returns a success flag and supplies the removed value through ByRef.

Continue this lesson.

You’re previewing NovaLearn without an account. Create a free account to read the rest.

Create free account