Free Web Site - Free Web Space and Site Hosting - Web Hosting - Internet Store and Ecommerce Solution Provider - High Speed Internet
Search the Web

Stack data structure

VB Articles


A stack is a data structure where you can only access the item at the top.  With a computer stack just like a stack of dishes you add items to the top and remove them from the top.  This behavior is know as LIFO (Last In First Out).

A stack can be implemented in Visual Basic using references to objects or using an array.  The array option is the easiest to implemented in VB and because we can dynamically resize an array in Visual Basic the stack can still grow and shrink.

The stack below is implemented in a class called "clsStack"

It has the following subs, functions and properties

  1. Push
    Place an item onto the stack
  2. Pop
    Return the item at the top of the stack and then remove it.
  3. Top
    Return the item at the top of the stack
  4. Count
    The number of items on the stack.

The code for it is shown below.

' A Stack implemented in an array
'
Private DataStack() As Variant
Private lStackSize As Long
Public Property Get Count() As Long
    Count = lStackSize
End Property
' Returns and removes the item
' at the top the stack
Public Function Pop() As Variant
    Pop = Top
    lStackSize = lStackSize - 1
    ReDim Preserve DataStack(lStackSize) ' Resize the array
End Function

'Adds data to the top of the stack
Public Sub Push(Data As Variant)
    ReDim Preserve DataStack(lStackSize) ' Resize the array
    DataStack(lStackSize) = Data
    lStackSize = lStackSize + 1
End Sub
' Returns the item at the top of the stack
Public Function Top() As Variant
    If lStackSize > 0 Then
        Top = DataStack(lStackSize - 1)
    Else
        Pop = Empty ' Stack empty
    End If
End Function

Example of using the stack class

When you run this code you will notice that the last item to be added is the first to be displayed.  The items are displayed "C", "B", "A"

Dim Stack As clsStack
Set Stack = New clsStack
    
Stack.Push "A"
Stack.Push "B"
Stack.Push "C"
Do While Stack.Count > 0
   MsgBox Stack.Pop
Loop