Skip to content
Snippets Groups Projects
Commit adf8dadb authored by ak6623's avatar ak6623
Browse files

Update file LinkedListExample.kt

parent 283d39e4
No related branches found
No related tags found
No related merge requests found
package lecture8
class LinkedList(){
var head: Node<T>? = null
class Node<T>(val data: T, var next: Node<T> = null){ //initialize it as null by default
fun add(node: Node<T>){
if (next == null) {
next = node
} else {
next?.add(null)
}
}
fun next() = next
}
fun add(t: T){
if(head == null){
head = Node (t)
} else {
head?.add(Node(t))
}
}
override fun toString(): String{
val sb = StringBuilder()
//iterate thorugh elements
sb.append("[")
sb.append(head.toString())
var current = head
while (current!=){
sb.append(", ")
sb.append(current.toString())
current = current.next
}
sb.append("]")
return sb.toString()
}
fun forEach(f: (T) -> Unit) {
f(head?.data)
var current = head?.next
while (current!=null){
//line to apply f to element
f(current?.data)
current = current.next
}
}
}
// if we want default arguments in a function, you want to put it at the end of all arguments, otherwise you have to use keywords(???)
fun main(){
val l = linkedList<Int>()
l.add(6)
l.add(12)
l.add(40009)
l.add(2)
println(l)
l.forEach {x -> println(x)}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment