< Previous lesson | Table of Content | Content of this Chapter | Next lesson >

Stack Data Structure

Stack is a dynamic set where the elements are added to the top of the set (Push) and deleted from the top of the set (Pop). You stack your variable on top of the others and get the last inputted variable. You use Stack data structure when you want to represent LIFO (Last-In First-Out) queuing. Example of this kind of queue is when you put things into a room with single door.

Visual Basic Tutorial

Creating Stack Library

Stack library consist of 2 methods: Push and Pop , and 2 properties: IsEmpty and Count .
1. Open a new standard Exe project
2. Right click in the project windows and Add Class Module
3. Change the name of the class module into Stack
4. Copy and paste the code below

Option Explicit

Private lngTop As Long
Private myStack() As Variant

' to manage increase of array
Private k As Integer
Private Const MAXARRAY = 5

Property Get Count() As Long
Count = lngTop
End Property

Property Get IsEmpty() As Boolean
If lngTop = 0 Then IsEmpty = True Else IsEmpty = False
End Property

Function Push(ByRef myStack, ByVal value)
lngTop = lngTop + 1

If lngTop > k * MAXARRAY Then
k = k + 1
ReDim Preserve myStack(0 To k * MAXARRAY)
End If
myStack(lngTop) = value
End Function

Function Pop(ByRef myStack)
If IsEmpty() Then
MsgBox "Stack underflow"
lngTop = lngTop - 1
Pop = myStack(lngTop + 1)
End If
End Function

Using Stack Library

  1. Continue the project by typing the following code into the form declaration section:

    Option Explicit
    Dim s As New Stack
    Dim myStack()

  2. Then in the MouseDown event procedure copy and paste the following procedure:

    Private Sub Form_MouseDown(Button As Integer, Shift As Integer, X As Single, y As Single)
    Dim q

    q = Array(X, y)
    If Button = vbLeftButton Then
    Call s.Push(myStack, q)
    q = s.Pop(myStack)
    End If
    End Sub

  3. Save the project and debug the program to see how it works. Check the value of q and MyStack

< Previous lesson | Table of Content | Content of this Chapter | Next lesson >