VB.Net program to implement stack using structure

Here, we are going to learn how to implement stack using structure in VB.Net?
Submitted by Nidhi, on January 12, 2021 [Last updated : March 08, 2023]

Implement stack using structure in VB.Net

Here, we implemented stack using structure. Stack follows LIFO (Last In First Out) property, which means last inserted elements, deleted first. Two basic operations are performed in Stack:

  1. PUSH: To insert an element into the stack.
  2. POP: To get and remove an element from the stack.

In the stack, we use an array to store elements, and a pointer top, that points topmost element in the stack.

Program/Source Code:

The source code to implement a stack using structure is given below. The given program is compiled and executed successfully.

VB.Net code to implement stack using structure

'VB.Net program to implement stack using structure.

Imports System.IO

Module Module1
    Structure Stack
        Private ele() As Integer
        Private top As Integer
        Private max As Integer

        Public Sub New(ByVal size As Integer)
            ReDim ele(size)
            top = -1
            max = size
        End Sub

        Public Sub push(ByVal item As Integer)
            If (top = max - 1) Then
                Console.WriteLine("Stack Overflow")
                top = top + 1
                ele(top) = item
            End If
        End Sub

        Public Function pop() As Integer
            Dim item As Integer = 0
            If (top = -1) Then
                Console.WriteLine("Stack Underflow")
                Return -1
                item = ele(top)
                top = top - 1
                Console.WriteLine("Poped element is: " & item)
                Return item
            End If
        End Function

        Public Sub printStack()
            If (top = -1) Then
                Console.WriteLine("Stack is Empty")
                For i = 0 To top Step 1
                    Console.WriteLine("Item(" & i + 1 & "): " & ele(i))
            End If
        End Sub
    End Structure

    Sub Main()
        Dim S As New Stack(5)


        Console.WriteLine("Items are : ")

    End Sub
End Module


Items are :
Item(1): 10
Item(2): 20
Item(3): 30
Item(4): 40
Item(5): 50
Poped element is: 50
Poped element is: 40
Poped element is: 30
Press any key to continue . . .


In the above program, we created a module Module1 that contains the Main() function. The Main() function is the entry point for the program, Here, we created a structure Stack that contains push(), pop(), and printStack() functions.

The push() function is used to store data elements into the stack. The pop() function is to get elements from the stack and print the item on the console screen. The printStack() function is used to print all items of the stack on the console screen.

VB.Net Data Structure Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.