Skip to content

Commit d8fd273

Browse files
committed
refine
1 parent f18f65b commit d8fd273

File tree

2 files changed

+8
-17
lines changed

2 files changed

+8
-17
lines changed

src/main.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,5 @@ pub mod n1_two_sum;
33
pub mod n2_add_two_numbers;
44

55
fn main() {
6+
67
}

src/n2_add_two_numbers.rs

Lines changed: 7 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,8 @@ pub struct Solution {}
5959
impl Solution {
6060
pub fn add_two_numbers(l1: Option<Box<ListNode>>, l2: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
6161
let (mut l1, mut l2) = (l1, l2);
62-
let mut curr = None;
62+
let mut dummy_head = Some(Box::new(ListNode::new(0)));
63+
let mut tail = &mut dummy_head;
6364
let (mut l1_end, mut l2_end, mut overflow) = (false, false, false);
6465
loop {
6566
let lhs = match l1 {
@@ -72,27 +73,14 @@ impl Solution {
7273
};
7374
// if l1, l2 end and there is not overflow from previous operation, return the result
7475
if l1_end && l2_end && !overflow {
75-
break Solution::reverse(curr);
76+
break dummy_head.unwrap().next
7677
}
7778
let sum = lhs + rhs + if overflow { 1 } else { 0 };
7879
let sum = if sum >= 10 { overflow = true; sum - 10 } else { overflow = false; sum };
79-
let mut node = ListNode::new(sum);
80-
node.next = curr;
81-
curr = Some(Box::new(node));
80+
tail.as_mut().unwrap().next = Some(Box::new(ListNode::new(sum)));
81+
tail = &mut tail.as_mut().unwrap().next
8282
}
8383
}
84-
85-
fn reverse(l: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
86-
let mut prev = None;
87-
let mut current = l;
88-
while let Some(mut current_node_inner) = current {
89-
let next = current_node_inner.next;
90-
current_node_inner.next = prev;
91-
prev = Some(current_node_inner);
92-
current = next;
93-
}
94-
prev
95-
}
9684
}
9785

9886
// submission codes end
@@ -106,5 +94,7 @@ mod tests {
10694
assert_eq!(Solution::add_two_numbers(to_list(vec![2, 4, 3]), to_list(vec![5, 6, 4])), to_list(vec![7, 0, 8]));
10795

10896
assert_eq!(Solution::add_two_numbers(to_list(vec![9, 9, 9, 9]), to_list(vec![9, 9, 9, 9, 9, 9])), to_list(vec![8, 9, 9, 9, 0, 0, 1]));
97+
98+
assert_eq!(Solution::add_two_numbers(to_list(vec![0]), to_list(vec![0])), to_list(vec![0]))
10999
}
110100
}

0 commit comments

Comments
 (0)