Kotlin 函数参数:Val 不能重新赋值 [英] Kotlin function parameter: Val cannot be reassigned
问题描述
我用 Kotlin 编写了红黑树.Fun insertFixup 在插入新元素后恢复平衡(z: Node? 是新元素).树平衡算法取自此处(第 2-3 页).问题是 Kotlin 不允许我将 z 重新分配给 z.parent 和 z.父.父.我希望 z 成为一个 指针.问题是如何让 Kotlin 理解我想从他那里得到什么?
I have written Red–black tree in Kotlin. Fun insertFixup restores balance after inserting new element (z: Node? is new element). Algorithm of tree balancing is taken from here (pages 2-3). The problem is that Kotlin does not allow me to reassign z to z.parent and z.parent.parent. I want z to be a pointer. The question is how to make Kotlin understand what I want from him?
class Node(key: Int) {...}
class BinarySearchTree {
var root: Node? = null
fun insert(newNode: Node) {...}
fun RotateLeft(x: Node?) {...}
fun RotateRight(x: Node?) {...}
fun insertFixup(z: Node?) {
var y: Node?
while (z?.parent?.color == "RED") {
if (z?.parent == z?.parent?.parent?.left) {
y = z?.parent?.parent?.right
if (y?.color == "RED") {
z?.parent?.color = "BLACK"
y?.color = "BLACK"
z?.parent?.parent?.color = "RED"
z = z?.parent?.parent
}
if (z == z?.parent?.right) {
z = z?.parent
RotateLeft(z)
z?.parent?.color = "BLACK"
z?.parent?.parent?.color = "RED"
RotateRight(z?.parent?.parent)
}
} else {
y = z?.parent?.parent?.left
if (y?.color == "RED") {
z?.parent?.color = "BLACK"
y?.color = "BLACK"
z?.parent?.parent?.color = "RED"
z = z?.parent?.parent
}
if (z != z?.parent?.left) {
z = z?.parent
RotateLeft(z)
z?.parent?.color = "BLACK"
z?.parent?.parent?.color = "RED"
RotateRight(z?.parent?.parent)
}
}
}
root?.color = "BLACK"
}
}
fun main(args: Array<String>) {
val bst = BinarySearchTree()
while (true) {
var newNode = Node(readLine()!!.toInt())
bst.insert(newNode)
bst.insertFixup(newNode)
}
}
UPD:谢谢大家!所有答案都很有帮助,我在您的回复中找到了解决方案.
UPD: Thanks to all! All the answers were helpful and I have found the solution in your replies.
推荐答案
Kotlin 中的函数参数基本上都是只读的 val
的函数内部,所以 z
在这里将始终引用传入的原始对象.
Function parameters in Kotlin are basically read-only val
's inside the function, so z
here will always refer to the original object that was passed in.
如果您需要在函数运行时修改它指向的内容,则必须在函数的开头制作它的本地副本,然后您可以将其设为 var
.
If you need to modify what it points to while your function is running, you'll have to make a local copy of it at the beginning of the function, and then you can make that a var
.
例如,您可以像这样启动您的函数,它可以让您稍后重新分配此本地 var
:
For example, you could start your function like this, which lets you reassign this local var
later:
fun insertFixup(_z: Node?) {
var z = _z
// ...
z = z.parent
// ...
}
这篇关于Kotlin 函数参数:Val 不能重新赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!