Reputation: 241
There is one thing I do not quite understand, for example:
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
Now when I do printlist(l1)
, it prints:
1 2 3
which is correct.
What if I set l2.next = nil
then printList(l1)
? The output is: 1 2
, which I can understand.
What I don't understand is if I set l2 = nil
then printList(l1)
, it still prints 1 2 3
.
Why does it not print 1
as the second node has become nil, so it should cut off the list?
Upvotes: 0
Views: 49
Reputation: 3323
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) <--|
Upvotes: 1
Reputation: 149
This is because L2 was referencing a node object in memory and setting it as L1.next also made L1.next refer to that same object in memory. So setting L2 to nil means L2 variable should no longer reference the node object but L1.next remains unchanged and still points to the node object.
Upvotes: 0