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

标签 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?.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

最佳答案

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

重点是,您实际上并没有调用 print 方法!您调用 Kotlin 的全局通用 print 方法,该方法仅打印 head.toString() 这是为什么?因为您的 print 方法需要不可为 null 的参数,并且您的 head 变量的类型为 Node?。因此,Kotlin 不会将调用与您的方法匹配,而是与接受可为 null 参数的库方法匹配。

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

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

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

顺便说一句,您的实现有一个错误,并且只会打印 2 3 4 5 ;)

关于kotlin - 如何在 Kotlin 链表中仅打印整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59974300/

相关文章:

c - 仅用一个指针删除链表的最后一个元素

java - 在 Kotlin 中对 Unit/void 做出这种假设是否安全?

kotlin - 你如何在 Kotlin Exposed 中实现表继承?

multithreading - Kotlin:如何调用可挂起函数而不等待其结果?

c++ - 自包含链表

C - 按字母顺序将新节点插入链表

c - 我想成对交换链表项,我的代码给出了段错误

c++ - 哈希表 - 链表数组 - C++

android-intent - intent.getStringExtra 不能为空 kotlin

kotlin - 如何仅在需要时读取Maven存储库凭据?