【发布时间】:2016-12-13 00:23:58
【问题描述】:
我正在尝试理解 Python 的传递参数的方式。我知道 Python 不同于 C++ 和其他语言。它是通过对象引用传递的。
我尝试使用这些代码:
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
如果我做 testWithPointers1(node1)
那么 node1.next 将是 None
def testWithPointers2(head):
cur = head
cur.next = None
如果我做 testWithPointers1(node1)
那么 node1.next 将是 None
def printLinkedList(head):
while head:
print(head.val)
head = head.next
但是为什么这段代码,在调用 printLinkedList(node1) 之后,不会改变 node1 的值呢?
【问题讨论】:
-
你没有将node1的下一个值赋给最后一位的任何东西?
标签: python loops linked-list