#445
Medium Algorithms Add two numbers ii
Linked List Math Stack
62.4% acceptance
Jan 13, 2026
6163
303
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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(n)
impl Solution {
pub fn add_two_numbers(l1: Option<Box<ListNode>>, l2: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
let mut stack1 = Vec::new();
let mut stack2 = Vec::new();
let mut curr = l1;
while let Some(node) = curr {
stack1.push(node.val);
curr = node.next;
}
let mut curr = l2;
while let Some(node) = curr {
stack2.push(node.val);
curr = node.next;
}
let mut result = None;
let mut carry = 0;
while !stack1.is_empty() || !stack2.is_empty() || carry > 0 {
let v1 = stack1.pop().unwrap_or(0);
let v2 = stack2.pop().unwrap_or(0);
let sum = v1 + v2 + carry;
carry = sum / 10;
let mut node = ListNode::new(sum % 10);
node.next = result;
result = Some(Box::new(node));
}
result
}
}