Created
February 7, 2021 05:41
-
-
Save nitinbhojwani/e5c740816b757588a9537af52f007784 to your computer and use it in GitHub Desktop.
Basic LinkedList implementation in Kotlin
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
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