How to reverse a singly linked list in-place in Kotlin

1 Answer

0 votes
// A mutable singly linked list node
data class ListNode(
    var value: Int,
    var next: ListNode? = null
)

// Reverse the linked list in-place
fun reverseList(head: ListNode?): ListNode? {
    var prev: ListNode? = null        // will become the new head
    var current: ListNode? = head     // pointer to traverse the list

    while (current != null) {
        val nextNode = current.next   // save next node
        current.next = prev           // reverse the link
        prev = current                // move prev forward
        current = nextNode            // move current forward
    }

    return prev  // prev is the new head
}

// Print the linked list
fun printList(head: ListNode?) {
    var temp = head
    while (temp != null) {
        print(temp.value)
        if (temp.next != null) print(" -> ")
        temp = temp.next
    }
    println()
}

fun main() {
    // Build a sample list: 1 -> 2 -> 3 -> 4 -> 5
    val head = ListNode(1,
        ListNode(2,
            ListNode(3,
                ListNode(4,
                    ListNode(5, null)
                )
            )
        )
    )

    println("Original list:")
    printList(head)

    // Reverse the list
    val reversed = reverseList(head)

    println("Reversed list:")
    printList(reversed)
}


/*
run:

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

*/

 



answered Jun 30 by avibootz
...