首页 > 解决方案 > 如何仅在 Kotlin 链表中打印整数

问题描述

我是 Kotlin 的初学者并面临这个问题。


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

生成的输出:Node(data=1, next=Node(data=2, next=Node(data=3, next=Node(data=4, next=Node(data=5, next=null)))))

预期产出:1 2 3 4 5

标签: kotlinlinked-list

解决方案


哇,一开始我不明白发生了什么,但现在我明白你的代码有可怕且难以检测的错误!

关键是,您实际上并没有调用您的print方法!你调用Kotlin's 的全局泛型print方法,它简单地打印head.toString()Why is that? 因为您的print方法需要不可为空的参数,并且您的head变量是Node?. 因此,Kotlin 没有将调用与您的方法匹配,而是与接受可为空参数的库方法匹配。

你必须改变你的方法签名,它接受Node?参数:

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

然后,您需要在方法中进行适当的更改。

在旁注中,您的实现有一个错误,只会打印2 3 4 5 ;)


推荐阅读