Home »
VB.Net »
VB.Net Programs
VB.Net program to implement stack using structure
By Nidhi Last Updated : November 15, 2024
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:
- PUSH: To insert an element into the stack.
- 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")
Else
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
Else
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")
Else
For i = 0 To top Step 1
Console.WriteLine("Item(" & i + 1 & "): " & ele(i))
Next
End If
End Sub
End Structure
Sub Main()
Dim S As New Stack(5)
S.push(10)
S.push(20)
S.push(30)
S.push(40)
S.push(50)
Console.WriteLine("Items are : ")
S.printStack()
S.pop()
S.pop()
S.pop()
End Sub
End Module
Output
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 . . .
Explanation
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 »