Skip to content

Add Two Numbers

Problem Description

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Solution

Approach

To solve this problem, we can iterate through both linked lists simultaneously, adding corresponding digits and handling carry-over when the sum of two digits exceeds 9. The result is stored in a new linked list.

Python Code

from typing import Optional

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        dummy = ListNode()  # A dummy node to simplify edge cases.
        current = dummy  # Current node in the new list.
        carry = 0  # Initialize the carry.

        # Traverse both lists until the end of both lists is reached.
        while l1 or l2 or carry:
            # Get the values from the current nodes or 0 if we've reached the end of a list.
            val1 = l1.val if l1 else 0
            val2 = l2.val if l2 else 0

            # Compute the new sum and carry.
            total = val1 + val2 + carry
            carry = total // 10  # Carry for the next position.
            new_digit = total % 10  # Digit to store in the new list.

            # Append the new digit to the result list.
            current.next = ListNode(new_digit)
            current = current.next

            # Move to the next nodes in l1 and l2 if they are available.
            if l1:
                l1 = l1.next
            if l2:
                l2 = l2.next

        return dummy.next  # Return the next of dummy as the head of the result list.