Skip to content

Instantly share code, notes, and snippets.

@AmniX
Created February 25, 2020 13:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AmniX/910b1d136de7b11801ee533656f03e85 to your computer and use it in GitHub Desktop.
Save AmniX/910b1d136de7b11801ee533656f03e85 to your computer and use it in GitHub Desktop.
LinkList Node In Kotlin with Helper Functions
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