简体   繁体   中英

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM