↻one more pass.
Linked lists · Medium

Add Two Numbers: the idea to remember.

Add two nonnegative numbers stored as reversed digit linked lists, returning reversed result digits.

Solve on LeetCode ↗

The core insight

Advance both lists together, emit sum modulo ten, and carry the quotient to the next position.

Why it works

At each position, the two digits plus incoming carry are precisely the contribution to that decimal place.

The mistake to avoid

Continue while either list or the carry remains; the lists may have different lengths.

Time: O(max(m,n))Space: O(max(m,n)) output

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

// Java reference adapted from neetcode-gh/leetcode (MIT).
// Advance both lists together, emit sum modulo ten, and carry the quotient to the next position.
public ListNode addTwoNumbers(ListNode first, ListNode second) {
    int q = 0;
    int r = 0;
    int sum = 0;
    ListNode head = null;
    ListNode temp = null;
    while (first != null || second != null || q>0) {
        sum =
            q +
            (
                ((first != null) ? first.val : 0) +
                ((second != null) ? second.val : 0)
            );
        r = sum % 10;
        q = sum / 10;
        ListNode newNode = new ListNode(r);
        if (head == null) {
            head = newNode;
        } else {
            temp = head;
            while (temp.next != null) {
                temp = temp.next;
            }
            temp.next = newNode;
            newNode.next = null;
        }
        if (first != null) {
            first = first.next;
        }
        if (second != null) {
            second = second.next;
        }
    }
    return head;
}

Java reference adapted from neetcode-gh/leetcode · MIT license

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.