I'm doing a question from LeetCode. I've found something that doesn't make much sense to me.
The question:
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.
My solution:
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
The confusion:
When I do curr = dummy , it seems that dummy is passed by reference and mutating curr mutates dummy. But the return statement return dummy.next is not the same value as return curr.next? Since curr = dummy, at the end of the loop, curr is at the end of the list, so shouldn't dummy also be at the end of the list? However, dummy is still at the very front of the list and dummy.next is the start of the list passed into the function but mutated in the correct way.
Also, when I do:
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 gets printed but END doesn't.
Can someone clear the confusion up for me?
curris the same asdummyinitially, yes, but you setcurr = ainside the loop, socurrwon't remain the same asdummy. You're setting it to something else. Search this site for many, many questions about Python value/reference, variables, name binding, etc.