2014-09-22 172 views
3

我最近开始学习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() 
} 

,我得到了以下错误:

Error:(22, 13) Kotlin: [Internal Error] org.jetbrains.jet.codegen.CompilationException: Back-end (JVM) Internal error: cannot store to value [email protected] 
Cause: cannot store to value [email protected] 
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 ... 

我已经在这里和在谷歌搜索,但我想不出是什么造成这个错误的问题

编辑: 所以我试图重新实现insert功能和使用requireNotNull()以避免样稿iler担心无效安全的东西。

下面是代码和它现在的工作:

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) 
    } 
} 
+0

你用什么版本的科特林的? – abacabadabacaba 2014-09-22 03:43:29

+0

@abacabadabacaba 0.8.11 – 2014-09-22 03:48:41

+0

注意:内部编译器错误是由于Kotlin的一个非常旧的beta版本。 – 2015-12-27 05:34:42

回答

3

我认为问题就出在这行:

cur?.next = Node(n) 

的问题是,编译器不知道该怎么做,如果curnull。目前,这会导致内部错误,但未来版本中可能为supported

现在,最好的解决方案是重写代码,以便编译器可以检查cur从不是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) 
} 
+0

在Kotlin中,您可以使用'!!'运算符:'a !!'而不是'requireNotNull(a)'。 – abacabadabacaba 2014-09-22 04:39:42