Skip to content

Instantly share code, notes, and snippets.

@odrianoaliveira
Created March 1, 2026 15:21
Show Gist options
  • Select an option

  • Save odrianoaliveira/9a6f05757b5cdabb9a1cdc3f69c84c8d to your computer and use it in GitHub Desktop.

Select an option

Save odrianoaliveira/9a6f05757b5cdabb9a1cdc3f69c84c8d to your computer and use it in GitHub Desktop.
package org.example
data class ListNode(var value: Int, var next: ListNode? = null)
// [val, next] -> [val, next] -> null
fun main() {
val head = buildLinkedList()
printListNodes(head)
println("reversed")
val reversedHead = reverseLinkedList(head)
printListNodes(reversedHead)
}
fun reverseLinkedList(head: ListNode?): ListNode? {
var prev: ListNode? = null
var current: ListNode? = head
var next: ListNode?
while (current != null) {
next = current.next
current.next = prev
prev = current
current = next
}
return prev
}
private fun printListNodes(head: ListNode?) {
var current = head
while (current != null) {
println(current.value)
current = current.next
}
}
private fun buildLinkedList(): ListNode? {
var head: ListNode? = null
for (i in 1..100) {
val next = head
head = ListNode(i, next)
}
return head
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment