在Scala中,我需要使用循环创建一个不可变的链表.就像是:
case class Node(element: Int, next: Node)
val linkedList = Node(1, Node(2, null))
val cycle = Node(3, cycle)
cycle.next // this should go back to the same element
Run Code Online (Sandbox Code Playgroud)
但它不起作用.如何使用循环创建不可变的链表?
使用延迟值和按名称参数来推迟初始化:
class Node(val element: Int, next_ : => Node) {
lazy val next = next_
}
lazy val root: Node =
new Node(1,
new Node(2,
new Node(3, root)
)
)
// tail-recursive print function as a bonus
def printRec(node: Node, depth: Int): Unit = if (depth > 0) {
println(node.element)
printRec(node.next, depth - 1)
}
printRec(root, 10)
Run Code Online (Sandbox Code Playgroud)
输出:
1
2
3
1
2
3
1
2
3
1
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
137 次 |
| 最近记录: |