我是 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/