0

I was doing this Leetcode test https://leetcode.com/problems/add-two-numbers/ and the javascript solution that I found online is

var addTwoNumbers = function(l1, l2) {
    

    let carry = 0;
    let previousNode = new ListNode();
    let headNode = previousNode;
    while (l1 || l2 || carry) {
    let val1 = 0;
    let val2 = 0;
    if (l1) {
        val1 = l1.val;
        l1 = l1.next;
    }
    if (l2) {
        val2 = l2.val;
        l2 = l2.next;
    }
    let sum = val1 + val2 + carry;
    carry = sum > 9 ? 1 : 0;
    let digit = sum % 10;
    let currentNode = new ListNode(digit);
    previousNode.next = currentNode;
    previousNode = currentNode;
    }
        
return headNode.next;
}

I do not undestand how headNode gets updated and has the right answer. I mean:

Step1 - we create the new variable previousNode as {val:0 , next: null}
Step2 - headNode is previousNode, which means {val:0 , next: null}
Step3 - we create the new variable currentNode as {val:digit1 , next: null}
Step4 - previousNode.next is set as the currentNode, therefore previousNode now is {val:0 , next: {val:digit1 , next: null}}
Step5 - we set previousNode as the currentNode so we can continue adding the next solutions, and now previousNode is {val:digit1 , next: null}

and here we continue with the steps of the while loop

Step6 - we create the new variable currentNode as {val:digit2 , next: null}
Step7 - previousNode.next is set as the currentNode, therefore previousNode now is {val:digit1 , next: {val:digit2 , next: null}}
Step8 - we set previousNode as the currentNode, and now previousNode is {val:digit2 , next: null}

.... and so on ...

Now, question: when did we updated headNode??? why this code works and headNode is something like {val: 0, next : (everything we need)} , and therefore calling headNode.next we get the right solution?

Thank you for the explanation!

Welbog
  • 59,154
  • 9
  • 110
  • 123
  • `headNode` holds a reference to `previousNode`. So, when `previousNode` changes, `headNode` will reference those changes. – Scott Marcus May 10 '22 at 12:08
  • but in this case headNode should not remain {val:0 , next: (stuff)}. For example, in step 8 our previousNode is {val:digit2 , next: null} , and if headNode is just a straight reference to previousNode shouldn't it now become {val:digit2 , next: null} too? – Enrico Cagliari May 10 '22 at 12:13
  • 1
    What you need is a better understanding of references. I suggest taking a look at this question and its answers: https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language – Welbog May 10 '22 at 14:47
  • @Welbog That is the answer that I needed! Now everything is more clear. Thank you a lot!! – Enrico Cagliari May 11 '22 at 00:10

0 Answers0