As asked
Given a singly linked list defined as a sealed class hierarchy in Kotlin, write a function that reverses it iteratively and returns the new head. Do not allocate any new nodes.
Sample answer outline
The iterative solution uses three pointers: prev, current, and next. It traverses the list, reversing each next pointer in place. A strong answer recognizes that the sealed class structure allows exhaustive pattern matching for empty-list handling and uses Kotlin idioms like apply or let for clarity.
Reference implementation (kotlin)
sealed class Node
object Empty : Node()
data class Cons(val value: Int, var next: Node) : Node()
fun reverse(head: Node): Node {
// implement here
}Expect these follow-ups
- How would you reverse it recursively in Kotlin and what is the stack depth risk?
- How would you write a test for this function using JUnit and asserting structural equality?