Skip to content

Instantly share code, notes, and snippets.

@henriquehorbovyi
Last active April 5, 2022 15:46
Show Gist options
  • Save henriquehorbovyi/49d443b317cd05a1f2092792eb13e8ad to your computer and use it in GitHub Desktop.
Save henriquehorbovyi/49d443b317cd05a1f2092792eb13e8ad to your computer and use it in GitHub Desktop.
operations for ListNode like classes
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