Search for a command to run...
Initialization
A dummy node fronts the result so the first real digit can be attached without a special case, and temp walks along behind it.
Dummy Node + Carry
1function addTwoNumbers(l1, l2) {2 // Dummy avoids a special case for the first digit3 const dummy = new ListNode();4 let temp = dummy;//carry: 05 let carry = 0;6 7 // Keep going while either list has digits, or a carry remains8 while (l1 !== null || l2 !== null || carry !== 0) {9 let sum = 0;10 11 if (l1 !== null) { sum += l1.val; l1 = l1.next; }12 if (l2 !== null) { sum += l2.val; l2 = l2.next; }13 sum += carry;14 15 carry = Math.floor(sum / 10);16 17 const node = new ListNode(sum % 10);18 temp.next = node;19 temp = temp.next;20 }21 22 return dummy.next;23}