Home > Software engineering >  Leetcode Solution Explanation
Leetcode Solution Explanation

Time:07-11

For the LeetCode Solution for the problem Add two numbers :

    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        dummyHead = ListNode(0)
        curr = dummyHead
        carry = 0
        while l1 != None or l2 != None or carry != 0:
            l1Val = l1.val if l1 else 0
            l2Val = l2.val if l2 else 0
            columnSum = l1Val   l2Val   carry
            carry = columnSum // 10
            newNode = ListNode(columnSum % 10)
            curr.next = newNode
            curr = newNode
            l1 = l1.next if l1 else None
            l2 = l2.next if l2 else None
        return dummyHead.next

How is the dummHead Object getting updated from the 2nd iteration since in the 1st iteration curr is updated to a new object curr = newNode

CodePudding user response:

Before curr is assigned the newNode, it first gets mutated by the previous statement:

curr.next = newNode

At that moment -- in the first iteration -- curr still references the node that dummyHead references, and so dummyHead.next is a assigned a node reference here. So newNode becomes the tail in a linked list.

In the next iterations the same happens with that tail: it gets mutated, and the linked list grows with one more node, ...etc.

CodePudding user response:

During the first iteration, dummHead is linked to a new node, let's say Node 0.

dummHead.next = Node 0

Then during the second iteration, Node 0 will be linked to the a new node, Node 1

Node 0.next = Node 1

By doing so, now when you call dummHead.next.next, it will give you Node1.

That's how you update the dummyHead object.

It's like :

dummyhead -> Node 0 -> Node 1 -> .... -> The last Node

  • Related