Add two numbers (digits in reverse order)

Add two numbers stored as linked lists of digits, least-significant digit first, carrying into the next node like adding on paper.

Time O(max(m, n))Space O(max(m, n))Code C#
Watch it animatedStep through it, with the running line highlighted. Free with an account.

The idea

Walk both lists together like adding two numbers by hand: add the two current digits plus any carry, write down the last digit, and carry the rest into the next column. Keep going as long as either list still has a digit or there is a carry left over.

Code

public static ListNode AddTwoNumbers(ListNode l1, ListNode l2) {
    var dummy = new ListNode(0);
    ListNode tail = dummy;
    int carry = 0;
    while (l1 != null || l2 != null || carry != 0) {
        int sum = (l1?.val ?? 0) + (l2?.val ?? 0) + carry;
        carry = sum / 10;
        tail.next = new ListNode(sum % 10);
        tail = tail.next;
        l1 = l1?.next; l2 = l2?.next;
    }
    return dummy.next;
}

Tips

In the .NET library

l1?.val ?? 0 reads a digit as 0 once that list has run out, so the shorter list does not need padding with explicit zero nodes.