Two numbers stored as reversed linked lists: walk both at once, add digit by digit like on paper, and carry the 1 into the next node.
▼The problem
LeetCode 2 (Medium). Two non-empty linked lists hold two non-negative integers, one digit per node, with the digits in reverse order (the ones digit first). Add the two numbers and return the sum as a linked list in the same form.
Examples (LeetCode's): l1 = [2,4,3], l2 = [5,6,4] → [7,0,8] (342 + 465 = 807; the example and the walkthrough), and [9,9,9,9,9,9,9] + [9,9,9,9] → [8,9,9,9,0,0,0,1] (9999999 + 9999 = 10009998: uneven lists, the carry ripples through every column and the last carry adds a node; scenes 6 to 8).
The solution
def addTwoNumbers(list1, list2):
dummy = tail = ListNode()
carry = 0
while list1 or list2 or carry:
a = list1.val if list1 else 0
b = list2.val if list2 else 0
total = a + b + carry
tail.next = ListNode(total % 10)
carry = total // 10
tail = tail.next
list1 = list1.next if list1 else None
list2 = list2.next if list2 else None
return dummy.nextTranscript
Add Two Numbers. Two linked lists each hold a number, one digit per node, in reverse: the first node is the ones digit, then the tens, then the hundreds. Add the two numbers and return the sum as a list in the same form.
Take two, four, three, and five, six, four. Read backward, that's three hundred forty-two plus four hundred sixty-five, which is eight hundred seven. So the answer is seven, zero, eight: ones digit first again.
The easy way is to turn each list into an integer, add them, and split the sum back into nodes. Fine for small lists. But a list can hold a hundred digits, and a sixty-four-bit integer holds only nineteen. Past that, it overflows.
So add the way you learned in school: column by column, from the ones. The reverse order helps: the ones digits sit at the heads, right where both lists begin. In each column, add the two digits and the carry. Keep the last digit of the total, and carry the tens to the next column.
Let's add them. Two plus five is seven, no carry. Four plus six is ten: write the zero, carry the one. Three plus four, plus that one, is eight. The answer grows a node per column: seven, zero, eight.
The lists can differ in length. Try seven nines plus four nines. Once the short list runs out, its missing digits count as zero. The carry ripples through every column, and the last carry grows one more node.
In code, a dummy node anchors the answer, and a tail follows its end. Loop while either list or the carry remains. Take each digit, or zero if that list is done. Append the total mod ten, carry the total divided by ten, and step forward. Then return the node after the dummy.
Each column is visited once, so the time is linear in the longer list. Besides the answer, we keep just a carry and a few pointers: constant extra space.
Line up the digits, add each column, carry the one. That's Add Two Numbers.