Skip to main content
Back to problems
#2
Medium Algorithms

Add two numbers

Linked List Math Recursion
48.0% acceptance
Feb 27, 2026
36379
7187
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

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn add_two_numbers(l1: Option<Box<ListNode>>, l2: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
    let mut dummy = Box::new(ListNode::new(0));
    let mut curr = &mut dummy;
    let mut carry = 0;
    let mut p = l1;
    let mut q = l2;

    while p.is_some() || q.is_some() || carry != 0 {
      let mut sum = carry;
      if let Some(node) = p {
        sum += node.val;
        p = node.next;
      }
      if let Some(node) = q {
        sum += node.val;
        q = node.next;
      }
      carry = sum / 10;
      curr.next = Some(Box::new(ListNode::new(sum % 10)));
      curr = curr.next.as_mut().unwrap();
    }

    dummy.next
  }
}