Kha*_*sam 6 linked-list kotlin
我最近开始学习 Kotlin,所以我决定在其中实现一些数据结构。所以,我尝试实现一个单链表:
package datastructures
public class LinkedList {
private data class Node(var nodeValue: Int, var next: Node? = null)
private var head: Node? = null
fun insert(n: Int) {
if(head == null) head = Node(n)
else {
var cur = head
while(cur?.next != null) {
cur = cur?.next
}
cur?.next = Node(n)
}
}
fun print() {
var cur = head
while(cur != null) {
print("${cur.nodeValue} ")
cur = cur?.next
}
}
}
fun main(args: Array<String>) {
val n = LinkedList()
n.insert(5)
n.insert(3)
n.print()
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
Error:(22, 13) Kotlin: [Internal Error] org.jetbrains.jet.codegen.CompilationException: Back-end (JVM) Internal error: cannot store to value org.jetbrains.jet.codegen.StackValue$OnStack@a0a447f
Cause: cannot store to value org.jetbrains.jet.codegen.StackValue$OnStack@a0a447f
File being compiled and position: (22,13) in C:/Users/Khaled/IdeaProjects/Kotlin/src/LinkedList.kt
PsiElement: cur?.next = Node(n)
The root cause was thrown at: StackValue.java:75
at org.jetbrains.jet.codegen.ExpressionCodegen.genQualified(ExpressionCodegen.java:243)
at org.jetbrains.jet.codegen.ExpressionCodegen.genStatement(ExpressionCodegen.java:262)
at ...
Run Code Online (Sandbox Code Playgroud)
我一直在这里和谷歌搜索,但我无法弄清楚导致此错误的问题是什么
编辑:
所以我试图重新实现该insert函数并使用requireNotNull()以避免让编译器担心空安全的东西。
这是代码,它现在正在运行:
fun insert(n: Int) {
if (head == null) head = Node(n)
else {
var cur = head!!
while (cur.next != null) {
cur = cur.next!!
}
cur.next = Node(n)
}
}
Run Code Online (Sandbox Code Playgroud)
我认为问题出在这一行:
cur?.next = Node(n)
Run Code Online (Sandbox Code Playgroud)
问题是编译器不知道 if curis 该怎么办null。目前,这会导致内部错误,但未来版本可能会支持此功能。
目前,最好的解决方案是重写代码,以便编译器可以检查curnever null。问题是编译器假设声明为的字段var可以随时更改,因此在检查之前需要将它们的值加载到局部变量中null:
var cur = head
if(cur == null) head = Node(n)
else {
var next = cur.next
while(next != null) {
cur = next
next = cur.next
}
cur.next = Node(n)
}
Run Code Online (Sandbox Code Playgroud)