如何仅在Kotlin链表中打印整数

如何仅在Kotlin链表中打印整数,kotlin,linked-list,Kotlin,Linked List,我是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?.n

我是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)
}
生成的输出:节点(数据=1,下一个=Node(数据=2,下一个=Node(数据=3,下一个=Node(数据=4,下一个=Node(数据=5,下一个=nullее)))


预期输出:123445哇,起初我不明白发生了什么,但现在我知道你的代码有可怕的、难以检测的bug

关键是,您实际上并没有调用
print
方法!您调用
Kotlin
的全局通用
print
方法,它只打印
head.toString()
为什么?因为
print
方法需要不可为空的参数,而
head
变量的类型为
Node?
。因此,Kotlin没有将调用与您的方法相匹配,而是与接受可空参数的库方法相匹配

您必须更改方法签名,使其接受
节点?
参数:

fun print(head : Node?) {
  ...
}
然后,您需要在方法内部进行适当的更改


另一方面,您的实现有一个bug,只能打印2 3 4 5;)

您应该了解有关数据类的更多信息

数据类是指只包含字段和用于访问字段的crud方法(getter和setter)的类。这些只是其他类使用的数据容器。这些类不包含任何附加功能,并且不能独立地对其拥有的数据进行操作

这是那篇文章的链接,试试这个