I'm a beginner in Kotlin and facing this issue.
data class Node(val data :Int, var next:Node?=null)
private var head :Node ?=null
fun insert(data:Int){
if(head==null)
{
head=Node(data)
}
else
{
var current = head
while (current?.next!=null)
{
current=current.next
}
current?.next=Node(data)
}
}
fun print(head : Node)
{
if(head==null){
println(" Node Nodes")
}
else{
var current = head
while (current.next!=null)
{
println(current.data.toString())
current= current?.next!!
}
}
}
fun main() {
for (i in 1..5){
insert(i)
}
print(head)
}
Generated Output : Node(data=1, next=Node(data=2, next=Node(data=3, next=Node(data=4, next=Node(data=5, next=null)))))
Expected Output: 1 2 3 4 5
Wow, I didn't understand what was happening at first, but now I understand that your code has terrible and hard to detect bug!
The point is, you don't actually call your
printmethod! You callKotlin's global genericprintmethod, which simply printshead.toString()Why is that? Because yourprintmethod expects non-nullable argument, and yourheadvariable is of typeNode?. Because of that, Kotlin didn't match the invocation with your method, but with library method that accepts nullable arguments.You have to change your method signature, that it accepts
Node?argument:Then you need to do appropriate changes inside your method.
On the side note, your implementation has a bug and will only print 2 3 4 5 ;)