How to reverse a singly linked list in-place in VB.NET

1 Answer

0 votes
Imports System

Module ReverseLinkedList

    ' Node class for singly linked list
    Public Class ListNode
        Public Property Value As Integer        ' data stored in the node
        Public Property listNext As ListNode    ' reference to the next node

        Public Sub New(val As Integer)
            Value = val
            listNext = Nothing
        End Sub
    End Class

    ' Reverse the linked list in-place
    Public Function ReverseList(head As ListNode) As ListNode
        Dim prev As ListNode = Nothing          ' will become the new head
        Dim current As ListNode = head          ' pointer to traverse the list
        Dim nextNode As ListNode = Nothing      ' temporary pointer to store next node

        While current IsNot Nothing
            nextNode = current.listNext         ' save next node
            current.listNext = prev             ' reverse the link
            prev = current                      ' move prev forward
            current = nextNode                  ' move current forward
        End While

        Return prev                             ' prev is the new head
    End Function

    ' Print the linked list
    Public Sub PrintList(head As ListNode)
        Dim temp As ListNode = head

        While temp IsNot Nothing
            Console.Write(temp.Value)
            If temp.listNext IsNot Nothing Then
                Console.Write(" -> ")
            End If
            temp = temp.listNext
        End While

        Console.WriteLine()
    End Sub

    Sub Main()
        ' Build a sample list: 1 -> 2 -> 3 -> 4 -> 5
        Dim head As New ListNode(1)
        head.listNext = New ListNode(2)
        head.listNext.listNext = New ListNode(3)
        head.listNext.listNext.listNext = New ListNode(4)
        head.listNext.listNext.listNext.listNext = New ListNode(5)

        Console.WriteLine("Original list:")
        PrintList(head)

        ' Reverse the list
        head = ReverseList(head)

        Console.WriteLine("Reversed list:")
        PrintList(head)
    End Sub

End Module
		


' run:
'
' Original list:
' 1 -> 2 -> 3 -> 4 -> 5
' Reversed list:
' 5 -> 4 -> 3 -> 2 -> 1
'

 



answered Jun 30 by avibootz
...