Two numbers are stored as linked lists, with digits in reverse order. Return their sum as a linked list in the same form.
DSA Animator › DSA Revision › Linked List › Add Two Numbers
Remember: reversed digits mean you can add from the head. Don't forget a final carry node. The video solves Add Two Numbers (LeetCode 2, Medium) with the Linked List Arithmetic pattern from the Linked List topic, and you can replay every step in the interactive Add Two Numbers animation.
Two numbers are stored as linked lists, with digits in reverse order. Return their sum as a linked list in the same form.
2, 4, 3 is 342, and 5, 6, 4 is 465. The sum is 807, so the answer is 7, 0, 8.
Converting the lists to integers can overflow for long lists. Instead, add digit by digit, like on paper.
The lowest digit comes first, which is exactly where addition starts. Add the two digits plus the carry, write the sum mod 10, and carry the rest. Keep going while either list or the carry remains.
2 plus 5 is 7, with no carry. 4 plus 6 is 10, so write 0 and carry 1. 3 plus 4 plus 1 is 8. The result is 7, 0, 8.
In code, use a dummy head and a carry variable. Loop while either list or the carry is left, adding the available digits. Append sum mod 10, and set carry to sum divided by 10. It's O of max of m and n time.
Remember: reversed digits mean you can add from the head. Don't forget a final carry node.