xue
xue

Reputation: 2475

Python loop a linked list, why is the original head not changed?

I am trying to understand Python's pass parameter's way. I know that Python is different from C++ and other languages. It is pass by object reference.

And I tried play with these code:

class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node4 = ListNode(4)
node5 = ListNode(5)

node1.next = node2
node2.next = node3
node3.next = node4
node4.next = node5


def testWithPointers1(head):
    head.next = None   

If I do testWithPointers1(node1)

then the node1.next would be None

def testWithPointers2(head):
    cur = head
    cur.next = None

If I do testWithPointers1(node1)

then the node1.next would be None

def printLinkedList(head):
    while head:
        print(head.val)
        head = head.next

But why this code , after calling printLinkedList(node1), it would not change the node1 value ?

Upvotes: 0

Views: 337

Answers (1)

Prune
Prune

Reputation: 77857

It doesn't change the node1 value, because all you did was to change the local copy of the node. In each routine, head is a local variable that points to the node you passed in. It is not an alias for node1; it's just another reference to the node.

When you change fields of the node, you're pointing to the actual memory locations where the node lives, so you see those changes when you refer to the same locations through node1. However, changing the value of head does not change the node1 reference.

Upvotes: 1

Related Questions