Skip to content

Instantly share code, notes, and snippets.

@harsh183
Last active April 17, 2021 11:03
Show Gist options
  • Select an option

  • Save harsh183/180856e9842302cacf431c6bac9bbe59 to your computer and use it in GitHub Desktop.

Select an option

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
// 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)))
}
@harsh183

Copy link
Copy Markdown
Author

You can easily add functions, iterators, whatever you want pretty easily. For example here is reduce

data class Node<T>(var value: T, var next: Node<T>?) {
  fun reduce(op: (acc: T, item: T) -> T): T {
    var result = value
    var node = next
    while(node != null) {
      result = op(result, node.value)
      node = node.next
    }
    
    return result
  }
}

...

val head = Node(1, null)
val second = Node(2, Node(3, null))  
head.next = second
val product = head.reduce {acc, item -> acc * item}
println(product)  // 6

@harsh183

harsh183 commented May 8, 2020

Copy link
Copy Markdown
Author

MIT License

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment