Last active
April 17, 2021 11:03
-
-
Save harsh183/180856e9842302cacf431c6bac9bbe59 to your computer and use it in GitHub Desktop.
Simple singly linked list using data classes in Kotlin using one line. Featuring data classes and null safety
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
// Linked list | |
data class Node<T>(var value: T, var next: Node<T>?); | |
fun main() { | |
val head = Node(1, null) | |
val second = Node(2, Node(3, null)) // two more (init multiple) | |
head.next = second | |
println(head.value) // 1 | |
println(head.next?.value) // 2 | |
println(head.next?.next?.value) // 3 | |
println(head.next?.next?.next?.value) // null | |
println(head) | |
// Node(value=1, next=Node(value=2, next=Node(value=3, next=null))) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can easily add functions, iterators, whatever you want pretty easily. For example here is
reduce