Two non-negative integers are stored as linked lists of digits in reverse order (ones digit first). Return their sum as a linked list in the same format.
add(a, b, carry) builds one digit node and recursively adds the rest of both lists with the new carry.
1function addTwoNumbers(l1: ListNode | null, l2: ListNode | null, carry = 0): ListNode | null {2if (!l1 && !l2 && !carry) return null;3const sum = (l1?.val ?? 0) + (l2?.val ?? 0) + carry;4const node = new ListNode(sum % 10);5node.next = addTwoNumbers(l1?.next ?? null, l2?.next ?? null, Math.floor(sum / 10));6return node;7}
2 + 5 + 0 = 7: digit 7.
Space: play/pause · ←/→: step