Skip to content

Instantly share code, notes, and snippets.

@nitinbhojwani
Created February 7, 2021 05:41
Show Gist options
  • Save nitinbhojwani/e5c740816b757588a9537af52f007784 to your computer and use it in GitHub Desktop.
Save nitinbhojwani/e5c740816b757588a9537af52f007784 to your computer and use it in GitHub Desktop.
Basic LinkedList implementation in Kotlin
class LinkedList<T>() {
private var head: Node<T>? = null
private var lastNodePointer: Node<T>? = null
public fun add(value: T) {
val node = Node<T>(value)
if (head == null) {
head = node
lastNodePointer = node
} else {
lastNodePointer?.next = node
lastNodePointer = node
}
}
public fun getHead() : Node<T>? {
return head
}
public fun print() {
var curr = getHead()
while (curr != null) {
print(curr.value.toString() + " ")
curr = curr.next
}
println()
}
}
class Node<T>(public val value: T) {
public var next: Node<T>? = null
}
fun main() {
val linkedList = LinkedList<Int>()
linkedList.add(1)
linkedList.add(2)
linkedList.add(3)
linkedList.print()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment