我正在做一道 LeetCode 的题。我发现了一些对我来说没有多大意义的东西。
问题:
Given a linked list, swap every two adjacent nodes and return its head.
For example, Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
我的解决方案:
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dummy = ListNode(0)
dummy.next = head
curr = dummy
while curr.next and curr.next.next:
a = curr.next
b = curr.next.next
curr.next = b
a.next = b.next
b.next = a
curr = a
return dummy.next
困惑:
当我执行 curr = dummy
时,似乎 dummy 是通过引用传递的,并且变异 curr
会变异 dummy
。但是return语句return dummy.next
和return curr.next
的值不一样?由于 curr = dummy
,在循环结束时,curr
位于列表的末尾,因此 dummy
不应该位于 list 的末尾?但是,dummy
仍然位于列表的最前面,dummy.next
是传递到函数中的列表的开头,但以正确的方式进行了突变。
另外,当我这样做时:
if curr is dummy:
print("BEGIN")
while curr.next and curr.next.next:
a = curr.next
b = curr.next.next
curr.next = b
a.next = b.next
b.next = a
curr = a
if curr is dummy:
print("END")
BEGIN
被打印,但 END
没有打印。
有人可以帮我解答疑惑吗?
最佳答案
当您进行赋值时,var = x
使var
指向x
。在此之后,它不会使指向同一对象的其他变量指向 x
。
考虑这个例子:
>>> a = {'p': 2}
>>> b = a
>>> b
{'p': 2}
>>> b['p'] = 4
>>> a
{'p': 4}
>>> b = {'q': 3}
>>> a
{'p': 4}
>>> b
{'q': 3}
或者这个:
>>> class Node:
... def __init__(self, nxt):
... self.nxt = nxt
... def __repr__(self):
... return '(Node => %s)' % self.nxt
...
>>> a = Node(Node(2))
>>> a
(Node => (Node => 2))
>>> b = a
>>> b
(Node => (Node => 2))
>>> a.nxt = Node(4)
>>> a
(Node => (Node => 4))
>>> b
(Node => (Node => 4))
>>> b = b.nxt
>>> a
(Node => (Node => 4))
>>> b
(Node => 4)
关于python - Python 中的引用和值传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45824437/