首页 > 解决方案 > 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 = nilprintList(l1),它仍然会打印1 2 3

为什么1当第二个节点变为 nil 时它不打印,所以它应该切断列表?

标签: swift

解决方案


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) <--|

推荐阅读