0

I was doing the following LeetCode exercise

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

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        if l1 and l2:
            if l1.val < l2.val:
                temp = head = ListNode(l1.val)
                l1 = l1.next
            else:
                temp = head = ListNode(l2.val)
                l2 = l2.next
            while l1 and l2:
                if l1.val < l2.val:
                    temp = temp.next = ListNode(l1.val)
                    #temp.next = temp = ListNode(l1.val)
                    l1 = l1.next
                else:
                    temp = temp.next = ListNode(l2.val)
                    #temp.next = temp = ListNode(l2.val)
                    l2 = l2.next
       ...

My question is why the lines temp = temp.next = ListNode(l1.val) and temp = temp.next = ListNode(l2.val) don't work and the commented lines right below them do?

vmp
  • 2,370
  • 1
  • 13
  • 17

1 Answers1

4

They mean fundamentally different things:

temp = temp.next = ListNode(l1.val)

is equivalent to:

_node = ListNode(l1.val)
temp = _node
temp.next = _node

Whereas

temp.next = temp = ListNode(l1.val)

is equivalent to:

_node = ListNode(l1.val)
temp.next = _node
temp = _node

The second one assigns the next property of the current temp node to a new node, then sets temp to be the new node, which is the correct behavior. The first sets temp to the new node, then sets its next property to be itself, which is incorrect.

Aplet123
  • 33,825
  • 1
  • 29
  • 55
  • So the assignments are done from left to right in python? – vmp Dec 28 '20 at 17:59
  • @vmp Yes they are. – Aplet123 Dec 28 '20 at 18:00
  • Why is the second version the correct one? What is the point of assigning a value to attribute of an object only to immediatly overwrite the identifier? – mapf Dec 28 '20 at 18:04
  • 1
    @mapf Because it's a linked list, so `temp` is already stored in the `next` attribute of the previous node, so mutating `temp` then reassigning it does actually have an effect. – Aplet123 Dec 28 '20 at 18:06
  • @Aplet123 Oh that makes sense.. the syntax looks counter-intuitive to me, but I think I see it now. Thanks! – mapf Dec 28 '20 at 18:11