kotlin - 如何仅在 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
解决方案
哇,一开始我不明白发生了什么,但现在我明白你的代码有可怕且难以检测的错误!
关键是,您实际上并没有调用您的print
方法!你调用Kotlin
's 的全局泛型print
方法,它简单地打印head.toString()
Why is that? 因为您的print
方法需要不可为空的参数,并且您的head
变量是Node?
. 因此,Kotlin 没有将调用与您的方法匹配,而是与接受可为空参数的库方法匹配。
你必须改变你的方法签名,它接受Node?
参数:
fun print(head : Node?) {
...
}
然后,您需要在方法中进行适当的更改。
在旁注中,您的实现有一个错误,只会打印2 3 4 5 ;)
推荐阅读
- oauth-2.0 - Dynamics 365 Web API 给出 401 错误?
- c# - 为我的项目对象启用 Google 存储签名 URL 上的 CORS
- perl - 如何转储散列引用后面的数据
- r - 在数据框R中合并具有相同模式名称的行
- r - 在 dplyr 分析中结合多个汇总统计信息
- python - Plotly subplot 生成两个具有相同数据的图,尽管轨迹包含不同的数据
- ssl - OpenSSL 和 CAPI - 证书冲突
- swift3 - Swift 4 迁移 - 从非协议、非类 AnyObject 继承
- node.js - 使用“node --inspect-brk index.js”时如何查找节点的源文件
- ios - UIView 多重变换