Created
March 1, 2026 15:21
-
-
Save odrianoaliveira/9a6f05757b5cdabb9a1cdc3f69c84c8d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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