VB.Net program to traverse the singly linked list

Here, we are going to learn how to traverse the singly linked list in VB.Net?
Submitted by Nidhi, on January 18, 2021 [Last updated : March 08, 2023]

Traversing a singly linked list in VB.Net

Here, we will implement a linked list and access each element of the list and print them on the console screen.

Program/Source Code:

The source code to traverse the singly linked list is given below. The given program is compiled and executed successfully.

VB.Net code to traverse the singly linked list

'VB.Net program to traverse the singly linked list.

Imports System

Module Module1
    Class ListNode
        Private item As Integer
        Private link As ListNode

        Public Sub New(ByVal value As Integer)
            item = value
            link = Nothing
        End Sub
        Public Function AddItem(ByVal value As Integer) As ListNode
            Dim node As New ListNode(value)
            If IsNothing(link) Then
                node.link = Nothing
                link = node
            Else
                Dim temp As ListNode
                temp = link
                node.link = temp
                link = node
            End If
            Return node
        End Function

        Public Sub ListTraverse()
            Dim node As ListNode
            node = Me
            While IsNothing(node) = False
                Console.WriteLine("-->" & node.item)
                node = node.link
            End While
        End Sub
    End Class

    Sub Main()
        Dim StartNode As New ListNode(101)

        Dim n1 As ListNode
        Dim n2 As ListNode
        Dim n3 As ListNode
        Dim n4 As ListNode

        n1 = StartNode.AddItem(102)
        n2 = n1.AddItem(103)
        n3 = n2.AddItem(104)
        n4 = n3.AddItem(105)

        Console.WriteLine("Traversing of Linked list:")
        StartNode.ListTraverse()
    End Sub
End Module

Output

Traversing of Linked list:
-->101
-->102
-->103
-->104
-->105
Press any key to continue . . .

Explanation

In the above program, we created a module Module1 that contains the ListNode class and Main() function.

The ListNode class contains a constructor, AddItem(), and ListTraverse() method.

The constructor is used to initialized the singly linked list, The AddItem() method is used to add an item into the list, and ListTraverse() method is used to traverse the list from start to end.

The Main() function is the entry point for the program, Here, we created the singly linked list and add items to the list and then traverse the list using ListTraverse() method and print the items on the console screen.

VB.Net Data Structure Programs »




Comments and Discussions!

Load comments ↻





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