VB.Net program to implement a stack

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

VB.Net – Stack

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 the 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.

VB.Net code to implement a stack

The source code to implement the stack is given below. The given program is compiled and executed successfully.

'VB.Net program to implement a stack.

Imports System.IO

Module Module1
    Class 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 Class

    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 class 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.