Bird
Raised Fist0
DSA Javaprogramming

Add Two Numbers Represented as Linked List in DSA Java

Choose your learning style10 modes available
Mental Model
Each linked list holds a number in reverse order, so adding them is like adding digits from right to left with carry.
Analogy: Imagine adding two numbers digit by digit on paper starting from the rightmost digit, carrying over when sum exceeds 9.
List1: 2 -> 4 -> 3 -> null
List2: 5 -> 6 -> 4 -> null
Each node holds one digit, least significant digit first.
Dry Run Walkthrough
Input: list1: 2->4->3, list2: 5->6->4
Goal: Add the two numbers represented by the lists and return the sum as a linked list in the same reversed order.
Step 1: Add first digits 2 + 5 = 7, no carry
Result: 7 -> null
Why: Start adding from the least significant digit
Step 2: Add second digits 4 + 6 = 10, carry 1
Result: 7 -> 0 -> null, carry = 1
Why: Sum exceeds 9, so carry 1 to next digit
Step 3: Add third digits 3 + 4 + carry 1 = 8, no carry
Result: 7 -> 0 -> 8 -> null
Why: Add carry to next digit sum
Result:
7 -> 0 -> 8 -> null (represents 807)
Annotated Code
DSA Java
class ListNode {
    int val;
    ListNode next;
    ListNode(int val) { this.val = val; }
}

public class AddTwoNumbers {
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummyHead = new ListNode(0);
        ListNode current = dummyHead;
        int carry = 0;
        while (l1 != null || l2 != null || carry != 0) {
            int val1 = (l1 != null) ? l1.val : 0;
            int val2 = (l2 != null) ? l2.val : 0;
            int sum = val1 + val2 + carry;
            carry = sum / 10;
            current.next = new ListNode(sum % 10);
            current = current.next;
            if (l1 != null) l1 = l1.next;
            if (l2 != null) l2 = l2.next;
        }
        return dummyHead.next;
    }

    public static void printList(ListNode node) {
        while (node != null) {
            System.out.print(node.val);
            if (node.next != null) System.out.print(" -> ");
            node = node.next;
        }
        System.out.println(" -> null");
    }

    public static void main(String[] args) {
        ListNode l1 = new ListNode(2);
        l1.next = new ListNode(4);
        l1.next.next = new ListNode(3);

        ListNode l2 = new ListNode(5);
        l2.next = new ListNode(6);
        l2.next.next = new ListNode(4);

        ListNode result = addTwoNumbers(l1, l2);
        printList(result);
    }
}
while (l1 != null || l2 != null || carry != 0) {
continue adding while any list has digits or carry remains
int val1 = (l1 != null) ? l1.val : 0;
get current digit from first list or 0 if none
int val2 = (l2 != null) ? l2.val : 0;
get current digit from second list or 0 if none
int sum = val1 + val2 + carry;
sum digits plus carry from previous step
carry = sum / 10;
calculate carry for next digit
current.next = new ListNode(sum % 10);
create new node with digit part of sum
current = current.next;
move pointer forward in result list
if (l1 != null) l1 = l1.next;
advance first list pointer
if (l2 != null) l2 = l2.next;
advance second list pointer
OutputSuccess
7 -> 0 -> 8 -> null
Complexity Analysis
Time: O(n) because we traverse both lists once where n is the longer list length
Space: O(n) because the result list can be at most one node longer than the longer input list
vs Alternative: Compared to converting lists to numbers and adding, this approach avoids integer overflow and works digit by digit
Edge Cases
One list is empty
Returns the other list as the sum
DSA Java
int val1 = (l1 != null) ? l1.val : 0;
Sum produces an extra carry digit
Adds a new node at the end for the carry
DSA Java
while (l1 != null || l2 != null || carry != 0) {
Lists of different lengths
Continues adding digits from longer list with carry
DSA Java
int val2 = (l2 != null) ? l2.val : 0;
When to Use This Pattern
When you see two linked lists representing numbers in reverse order and need to add them digit by digit, use this pattern to handle carry and different lengths.
Common Mistakes
Mistake: Not handling carry after processing all nodes
Fix: Include carry in while loop condition to add extra node if needed
Mistake: Advancing list pointers without checking for null
Fix: Check if pointer is not null before moving to next node
Summary
Adds two numbers represented by linked lists digit by digit with carry.
Use when numbers are stored in reverse order in linked lists and you need their sum as a linked list.
The key insight is to add digits like on paper, carrying over when sum exceeds 9.

Practice

(1/5)
1. What does the problem "Add Two Numbers Represented as Linked List" mainly involve?
easy
A. Reversing a linked list
B. Sorting two linked lists in ascending order
C. Finding the middle node of a linked list
D. Adding digits node by node from two linked lists representing numbers

Solution

  1. Step 1: Understand the problem context

    The problem involves two linked lists where each node contains a digit of a number, stored in reverse order.
  2. Step 2: Identify the required operation

    We need to add these two numbers digit by digit, handling carry, and return the sum as a linked list.
  3. Final Answer:

    Adding digits node by node from two linked lists representing numbers -> Option D
  4. Quick Check:

    Adding digits node by node = D [OK]
Hint: Focus on digit-wise addition with carry [OK]
Common Mistakes:
  • Confusing addition with sorting
  • Ignoring carry during addition
  • Assuming numbers are stored in forward order
2. Which of the following Java code snippets correctly initializes a new node for a singly linked list representing a digit?
easy
A. ListNode node = ListNode(5);
B. ListNode node = new ListNode(); node.next = 5;
C. ListNode node = new ListNode(5);
D. ListNode node = new ListNode.val(5);

Solution

  1. Step 1: Recall Java object creation syntax

    In Java, to create a new object, use the 'new' keyword followed by the constructor call with parameters.
  2. Step 2: Check each option for correct syntax

    ListNode node = new ListNode(5); uses 'new ListNode(5);' which is correct. ListNode node = ListNode(5); misses 'new'. ListNode node = new ListNode(); node.next = 5; incorrectly sets next instead of val. ListNode node = new ListNode.val(5); is invalid syntax.
  3. Final Answer:

    ListNode node = new ListNode(5); -> Option C
  4. Quick Check:

    Java new object syntax = B [OK]
Hint: Use 'new' keyword with constructor for object creation [OK]
Common Mistakes:
  • Omitting 'new' keyword
  • Incorrect constructor call syntax
  • Trying to call constructor like a method without 'new'
  • Confusing node.val and node.next
3. What is the output linked list after adding the two numbers represented by these linked lists? List 1: 2 -> 4 -> 3 -> null (represents 342) List 2: 5 -> 6 -> 4 -> null (represents 465)
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode dummy = new ListNode(0);
    ListNode p = l1, q = l2, curr = dummy;
    int carry = 0;
    while (p != null || q != null) {
        int x = (p != null) ? p.val : 0;
        int y = (q != null) ? q.val : 0;
        int sum = carry + x + y;
        carry = sum / 10;
        curr.next = new ListNode(sum % 10);
        curr = curr.next;
        if (p != null) p = p.next;
        if (q != null) q = q.next;
    }
    if (carry > 0) {
        curr.next = new ListNode(carry);
    }
    return dummy.next;
}
medium
A. 7 -> 0 -> 8 -> null
B. 8 -> 0 -> 7 -> null
C. 7 -> 10 -> 7 -> null
D. 2 -> 4 -> 3 -> 5 -> 6 -> 4 -> null

Solution

  1. Step 1: Add digits node by node with carry

    Adding 2+5=7 (carry 0), 4+6=10 (carry 1), 3+4=7 plus carry 1 = 8.
  2. Step 2: Construct the resulting linked list

    Digits are 7 (units), 0 (tens), 8 (hundreds), so linked list is 7 -> 0 -> 8 -> null.
  3. Final Answer:

    7 -> 0 -> 8 -> null -> Option A
  4. Quick Check:

    342 + 465 = 807 represented as 7->0->8 [OK]
Hint: Add digits with carry, build new nodes [OK]
Common Mistakes:
  • Ignoring carry in addition
  • Appending nodes incorrectly
  • Mixing digit order in output
4. Identify the bug in this code snippet for adding two numbers represented as linked lists:
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode dummy = new ListNode(0);
    ListNode curr = dummy;
    int carry = 0;
    while (l1 != null && l2 != null) {
        int sum = carry + l1.val + l2.val;
        carry = sum / 10;
        curr.next = new ListNode(sum % 10);
        curr = curr.next;
        l1 = l1.next;
        l2 = l2.next;
    }
    if (carry > 0) {
        curr.next = new ListNode(carry);
    }
    return dummy.next;
}
medium
A. The carry is not calculated correctly
B. The while loop should use '||' instead of '&&' to handle different length lists
C. The dummy node is not initialized properly
D. The function does not return the correct node

Solution

  1. Step 1: Analyze the loop condition

    The loop uses '&&' which stops when either list ends, missing remaining nodes of longer list.
  2. Step 2: Correct loop condition to '||'

    Using '||' ensures the loop continues until both lists are fully processed, handling different lengths correctly.
  3. Final Answer:

    The while loop should use '||' instead of '&&' to handle different length lists -> Option B
  4. Quick Check:

    Loop condition must cover all nodes = A [OK]
Hint: Use '||' to process all nodes in both lists [OK]
Common Mistakes:
  • Using '&&' causing early loop exit
  • Not handling carry after loop
  • Not advancing pointers correctly
5. Given two linked lists representing numbers in reverse order, how would you modify the addition algorithm to handle the case where the input lists are extremely long (millions of nodes) and memory is limited?
hard
A. Use iterative addition with constant extra space and process nodes one by one
B. Convert linked lists to integers, add, then convert back to linked list
C. Store all digits in arrays before adding to optimize speed
D. Reverse both lists first, add, then reverse the result

Solution

  1. Step 1: Consider memory constraints with large inputs

    Converting to integers or arrays requires large memory, not feasible for millions of nodes.
  2. Step 2: Use iterative addition with constant extra space

    Process nodes one by one, create result nodes on the fly, and avoid storing entire numbers in memory.
  3. Final Answer:

    Use iterative addition with constant extra space and process nodes one by one -> Option A
  4. Quick Check:

    Iterative node-wise addition saves memory = C [OK]
Hint: Add nodes one by one without full number conversion [OK]
Common Mistakes:
  • Trying to convert entire list to integer causing overflow
  • Using extra arrays increasing memory usage
  • Reversing lists unnecessarily increasing complexity
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard