1// Definition for singly-linked list.
2// #[derive(PartialEq, Eq, Clone, Debug)]
3// pub struct ListNode {
4// pub val: i32,
5// pub next: Option<Box<ListNode>>
6// }
7//
8// impl ListNode {
9// #[inline]
10// fn new(val: i32) -> Self {
11// ListNode {
12// next: None,
13// val
14// }
15// }
16// }
17impl Solution {
18 pub fn add_two_numbers(
19 mut l1: Option<Box<ListNode>>,
20 mut l2: Option<Box<ListNode>>,
21 ) -> Option<Box<ListNode>> {
22 let mut result = Box::new(ListNode::new(0));
23 let mut tail = &mut result;
24 let mut carry = 0;
25
26 while l1.is_some() || l2.is_some() || carry > 0 {
27 let x = l1.as_ref().map(|n| n.val).unwrap_or(0);
28 let y = l2.as_ref().map(|n| n.val).unwrap_or(0);
29
30 let s = x + y + carry;
31 carry = s / 10;
32
33 tail.next = Some(Box::new(ListNode::new(s % 10)));
34 tail = tail.next.as_mut().unwrap();
35
36 l1 = match l1 {
37 Some(node) => node.next,
38 None => None,
39 };
40
41 l2 = match l2 {
42 Some(node) => node.next,
43 None => None,
44 };
45 }
46
47 return result.next;
48 }
49}
50