swift - Swift singlelinkedlist 节点未切断列表
问题描述
有一件事我不太明白,例如:
public class Node {
var val:Int
var next:Node?
init(_ val:Int) {
self.val = val
self.next = nil
}
}
func printList(_ node:Node?) {
var cur = node
while cur != nil {
print(cur!.val, terminator: " ")
cur = cur.next
}
}
var l1 = Node(1)
var l2 = Node(2)
var l3 = Node(3)
l1.next = l2
l2.next = l3
现在,当我这样做时printlist(l1)
,它会打印:
1 2 3
哪个是对的。
如果我设置l2.next = nil
然后printList(l1)
呢?输出是:1 2
,我可以理解。
我不明白的是,如果我设置l2 = nil
了printList(l1)
,它仍然会打印1 2 3
。
为什么1
当第二个节点变为 nil 时它不打印,所以它应该切断列表?
解决方案
The variable l2 is a reference to the Node(2) object. Setting l2 to nil does not affect the object itself, only removes that reference. Node(1).next still references Node(2) and Node(2).next still references Node(3)
You might picture the initial setup like this
l1 -> Node(1) | v l2 -> Node(2) | v l3 -> Node(3)
And after setting l2 to nil, like this
l1 -> Node(1) | v Node(2) | v l3 -> Node(3)
Neither l2, nor l3 for that matter, are relevant when evaluating printlist(l1)
If the intent is to remove Node(2) from the list update Node(1).next to Node(3). eg.
l1.next = l3
You picture looks like this:
l1 -> Node(1) ---| | | l2 -> Node(2) | | | l3 -> Node(3) <--|
推荐阅读
- php - 如何在没有 google 或 wordpress 的情况下替代 google recapture?
- python - 如何将验证功能链接到收据
- delphi - 从 INI 文件中读取所有部分并添加到列表 delphi
- docker - 无法从 Docker 桌面删除 Docker 容器
- python - 为什么我的关联规则挖掘的 Apriori 函数将特征名称更改为 a、b、c....z?
- javascript - 如何通过比较打字稿中的不同字段对对象数组进行排序
- javascript - 如何从给定坐标中获取中心坐标?
- r - R 多对多减法
- javascript - WorkerError 发生在“下一次构建”
- python - 从列表中查找和替换屏幕坐标