Skip to content
BytePatterns

Add Two Digit Chains

MediumLinked Lists#dummy-node#carry-propagation~25m

Problem

Two non-negative whole numbers are stored as linked lists of single digits, with the least significant digit at the head. Add the two numbers and return the sum in the same format. The two lists may have different lengths, and neither carries a leading zero, meaning the last node is never a zero unless the number is zero itself.

Examples

Input:  a = 2 -> 4 -> 3, b = 5 -> 6 -> 4
Output: 7 -> 0 -> 8
Why:    342 plus 465 is 807, still written back to front
Input:  a = 9 -> 9, b = 1
Output: 0 -> 0 -> 1
Why:    edge case, the carry runs off the end and adds a digit
Input:  a = 0, b = 0
Output: 0
Why:    the sum of two zeros is a single zero digit

Hints

0 / 3

Stuck on the idea rather than the code? Singly Linked List Basics covers it.