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!