Created
February 25, 2020 13:03
-
-
Save AmniX/910b1d136de7b11801ee533656f03e85 to your computer and use it in GitHub Desktop.
LinkList Node In Kotlin with Helper Functions
This file contains 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 Node<T>(var value : T, var next : Node<T>? = null){ | |
override fun toString():String{ | |
val result = StringBuilder() | |
var next = this.next | |
result.append(value) | |
while(next != null){ | |
result.append(", ") | |
result.append(next.value) | |
next = next.next | |
} | |
return result.toString() | |
} | |
fun reverse():Node<T>?{ | |
var prev : Node<T>? = null | |
var curr : Node<T>?= this | |
var next : Node<T>? = null | |
while (curr != null){ | |
next = curr.next | |
curr.next = prev | |
prev = curr | |
curr = next | |
} | |
return prev | |
} | |
fun forEach(unit:(T)->Unit){ | |
var tmpNext : Node<T>?= this.next | |
unit(value) | |
while(tmpNext != null){ | |
unit(tmpNext.value) | |
tmpNext = tmpNext.next | |
} | |
} | |
fun size():Int{ | |
var i = 1 | |
forEach{ | |
i++ | |
} | |
return i | |
} | |
companion object{ | |
fun <T> of(initial : T, vararg values : T) : Node<T>{ | |
val result = Node(initial) | |
var next : Node<T>? = null | |
values.forEach{ | |
if(next == null){ | |
next = Node(it) | |
result.next = next | |
} else{ | |
next?.next = Node(it) | |
next = next?.next | |
} | |
} | |
return result | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment