How to print integer only in Kotlin Linked List

257 Views Asked by At

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

2

There are 2 best solutions below

0
xinaiz On BEST ANSWER

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 print method! You call Kotlin's global generic print method, which simply prints head.toString() Why is that? Because your print method expects non-nullable argument, and your head variable is of type Node?. 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:

fun print(head : Node?) {
  ...
}

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 ;)

0
aspmm On

You should learn more about data class.

A data class refers to a class that contains only fields and crud methods for accessing them (getters and setters). These are simply containers for data used by other classes. These classes do not contain any additional functionality and cannot independently operate on the data that they own.

Here's the link for that article,Try this https://android.jlelse.eu/kotlin-for-android-developers-data-class-c2ad51a32844