Last active
April 5, 2022 15:46
-
-
Save henriquehorbovyi/49d443b317cd05a1f2092792eb13e8ad to your computer and use it in GitHub Desktop.
operations for ListNode like classes
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
data class Node<T>(var value: T, var next: Node? = null) | |
fun <T> buildNodeList(vararg items: T): Node<T>? { | |
if (items.isEmpty()) | |
return null | |
val head = Node(items.first()) | |
if (items.size == 1) return head | |
var previous = head | |
for (i in 1 until items.size) { | |
val currentNode = Node(items[i]) | |
previous.next = currentNode | |
previous = currentNode | |
} | |
return head | |
} | |
fun <T> Node<T>.forEach(block: (Node<T>) -> Unit) { | |
var current: Node<T>? = this | |
while (current != null) { | |
block(current) | |
current = current.next | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment