pub fn add_two_numbers(mut left: Option<Box<Node>>,mut right: Option<Box<Node>>) -> Option<Box<Node>> {
let mut dummy = Box::new(Node::new(0));
let mut current = &mut dummy;
let mut carry = 0;
while left.is_some() || right.is_some() {
carry /= 10;
if let Some(mut node) = left {
carry += node.val;
left = node.next.take();
} else {
left = None;
}
if let Some(mut node) = right {
carry += node.val;
right = node.next.take();
} else {
right = None;
}
current.next = Some(Box::new(Node::new(carry % 10)));
current = current.next.as_mut().unwrap();
}
if carry / 10 == 1 {
current.next = Some(Box::new(Node::new(1)));
}
dummy.next
}
pub struct Node {
pub val: i32,
pub next: Option<Box<Node>>,
}
impl Node {
pub fn new(x: i32) -> Self {
Self {
val: x,
next: None,
}
}
}
pub fn from_vec(v: Vec<i32>) -> Option<Box<Node>> {
let mut head = None;
for x in v.into_iter().rev() {
let mut node = Box::new(Node::new(x));
node.next = head;
head = Some(node);
}
head
}
pub fn to_vec(mut head: Option<Box<Node>>) -> Vec<i32> {
let mut result = Vec::new();
while let Some(node) = head {
result.push(node.val);
head = node.next;
}
result
}