1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
|
fn main() {
let list1 = Some(Box::new(ListNode {
val: 2,
next: Some(Box::new(ListNode {
val: 4,
next: Some(Box::new(ListNode { val: 3, next: None })),
})),
}));
let list2 = Some(Box::new(ListNode {
val: 5,
next: Some(Box::new(ListNode {
val: 6,
next: Some(Box::new(ListNode { val: 4, next: None })),
})),
}));
Solution::add_two_numbers(list1, list2);
}
struct Solution(());
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ListNode {
pub val: i32,
pub next: Option<Box<ListNode>>,
}
impl ListNode {
#[inline]
fn new(val: i32) -> Self {
ListNode { next: None, val }
}
}
impl Solution {
pub fn add_two_numbers(
l1: Option<Box<ListNode>>,
l2: Option<Box<ListNode>>,
) -> Option<Box<ListNode>> {
let ans = Self::double_walker(l1, l2, false);
ans
}
fn double_walker(
l1: Option<Box<ListNode>>,
l2: Option<Box<ListNode>>,
carry: bool,
) -> Option<Box<ListNode>> {
if let (None, None) = (&l1, &l2) {
if carry {
return Some(Box::new(ListNode::new(1)));
} else {
return None;
}
}
let mut node = ListNode::new(0);
if let Some(n1) = &l1 {
node.val += n1.val;
}
if let Some(n2) = &l2 {
node.val += n2.val;
}
if carry {
node.val += 1;
}
node.next = Self::double_walker(
l1.and_then(|n| n.next),
l2.and_then(|n| n.next),
node.val >= 10,
);
if node.val >= 10 {
node.val = node.val - 10;
}
Some(Box::new(node))
}
}
|