Add Two Numbers — Linked List
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
const addTwoNumbers = function (l1, l2) { const ans = new ListNode(0); let cur = ans; let carry = 0; while (l1 || l2) { let first = (l1 && l1.val) || 0; let second = (l2 && l2.val) || 0; let sum = first + second + carry; cur.next = new ListNode(sum % 10); carry = Math.floor(sum / 10); cur = cur.next; l1 = l1 && l1.next; l2 = l2 && l2.next; } if (carry > 0) { cur.next = new ListNode(carry); } return ans.next; };
Don't forget to consider the carry at the last iteration. You might still have some left over carry that is not appended to the list yet.
Or, you could make the carry as a part of your loop. Until l1, l2 or carry remains, run the loop. This will make sure the "last" carry is handled and added to the list.