Linked list- current vs. current.next when appending

Question:

Node:

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

def add() part one:

def add(self, newData):
    
    if self.head is None:
        self.head = Node(newData)
        return
  
    current = self.head
   

def add() part 2

Why does this work?

    while current.next:
        current = current.next
    
    current.next =  Node(newData)

And this doesn’t?

    while current:
        current = current.next
            
    current = Node(newData)

Aren’t "current.next" in first one and "current" in second one same?

Asked By: LosProgramer

||

Answers:

The only difference between the two loop codes is the last line, where you either assign to current.next or to current. Those do fundamentally different things.

When you assign to current.next, you’re modifying an attribute of the Node object referenced by current. That change happens in place, so you’ll see the change through other references (like the chain of nodes earlier in the list). That’s what you want to happen.

In the modified version, when you assign to current, you’re only rebinding the variable name in the local namespace. You’re not changing any node! You could compare it to:

a = 1
b = a
b = 2
print(a) # still prints 1

Here b is current in the second version of your code. a is the next attribute of the last node of the list (which was called current.next in the working version of the code). Rebinding the local name b doesn’t change the other reference to the same value.

Answered By: Blckknght
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.