Group Group Group Group Group Group Group Group Group

One question about linklist node

#1

there is one thing I am 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 I use printlist(l1)
it print
1 2 3
which is right

what if I set
l2.next = nil
then printList(l1)
which show 1 2

which I can understand

what I dont understand

if I set

l2 = nil

then to printList(l1)

it still print
1 2 3

why not just print
1

as the second node has become nil, it should cut off the list

something I misunderstanding here?

#2

@kelvin_lau Can you please help with this when you get a chance? Thank you - much appreciated! :]

#3

This is about using reference variables to refer to objects.

This line creates a new node and makes l2 a reference to it:
var l2 = Node(2)

This line makes l1.next a reference to the same node:
l1.next = l2

When you set l2 to nil, l2 is no longer a reference to the node, but l1.next still is. The node itself will stick around as long as some variable has a reference to it.

The printlist() method starts with l1 and follows the chain of next references. It is not using the l2 or l3 references.

#4

The linked list should always point to null as the last element so that you know you have arrived at the end of the line. So to begin with when you initialize it you make it’s next element null since it is the last element to begin with.

#5

What @sgerrard said is correct.

To unlink the 1 from the rest of the list, you’d write l1.next = nil.

#6

so another question ,what is the best way to clear all the node in the linklist from memory?

for above example l1->l2-l3

#7

@kelvin_lau Can you please help with this when you get a chance? Thank you - much appreciated! :]

#8

In Swift, memory management is handled by ARC.

As long as a node has no more references pointing to it, it’ll be deallocated. For the linked list, simply removing the reference to the list would deallocate the entire list.