Algo-Sim › Linked Lists

Add Two Numbers

Medium · Linked Lists · step through it in Java, Python and C++ on your own input

Add two numbers stored as reversed digit lists, building the sum list node by node with a carry.

Problem

Two non-negative integers are stored as linked lists of digits, least significant digit first (342 is 2 → 4 → 3). Return their sum as a list in the same format.

Constraints

Edge cases to test

Follow-up questions

What if the digits are stored most significant first?
Reverse both lists first, or push digits onto two stacks and build the result from the front (LC 445): O(m + n).
Why not convert to integers?
The lists can be longer than any fixed-width integer.

Solution

Java

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

Python

def add_two_numbers(l1, l2):
    dummy = tail = ListNode()
    carry = 0
    while l1 or l2 or carry:
        total = carry
        if l1:
            total += l1.val
            l1 = l1.next
        if l2:
            total += l2.val
            l2 = l2.next
        carry = total // 10
        tail.next = ListNode(total % 10)
        tail = tail.next
    return dummy.next

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
        ListNode *dummy = new ListNode(0), *tail = dummy;
        int carry = 0;
        while (l1 != nullptr || l2 != nullptr || carry != 0) {
            int sum = carry;
            if (l1 != nullptr) {
                sum += l1->val;
                l1 = l1->next;
            }
            if (l2 != nullptr) {
                sum += l2->val;
                l2 = l2->next;
            }
            carry = sum / 10;
            tail->next = new ListNode(sum % 10);
            tail = tail->next;
        }
        return dummy->next;
    }
};

More Linked Lists problems