给定两个非空链表逆序存储的的非负整数,每个节点只存储一位数组。
请你把两个链表相加以下相同方法返回链表,保证两个数都不会以 0 开头。
数据范围: ,每个节点的值都满足
/** * #[derive(PartialEq, Eq, Debug, Clone)] * pub struct ListNode { * pub val: i32, * pub next: Option<Box<ListNode>> * } * * impl ListNode { * #[inline] * fn new(val: i32) -> Self { * ListNode { * val: val, * next: None, * } * } * } */ struct Solution{ } impl Solution { fn new() -> Self { Solution{} } /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param l1 ListNode类 * @param l2 ListNode类 * @return ListNode类 */ pub fn ListAdd(&self, l1: Option<Box<ListNode>>, l2: Option<Box<ListNode>>) -> Option<Box<ListNode>> { // write code here let mut result_dummy_head = Some(Box::new(ListNode::new(233))); let mut r_p = &mut result_dummy_head; let mut n1_p = &l1; let mut n2_p = &l2; let mut carry = 0; while n1_p.is_some() && n2_p.is_some() { let mut result_val = n1_p.as_ref().unwrap().val + n2_p.as_ref().unwrap().val + carry; carry = result_val / 10; result_val %= 10; r_p.as_mut().unwrap().next = Some(Box::new(ListNode::new(result_val))); r_p= &mut r_p.as_mut().unwrap().next; n1_p=&n1_p.as_ref().unwrap().next; n2_p=&n2_p.as_ref().unwrap().next; } while n1_p.is_some() { let mut result_val = n1_p.as_ref().unwrap().val + carry; carry = result_val / 10; result_val %= 10; r_p.as_mut().unwrap().next = Some(Box::new(ListNode::new(result_val))); r_p= &mut r_p.as_mut().unwrap().next; n1_p=&n1_p.as_ref().unwrap().next; } while n2_p.is_some() { let mut result_val = n2_p.as_ref().unwrap().val + carry; carry = result_val / 10; result_val %= 10; r_p.as_mut().unwrap().next = Some(Box::new(ListNode::new(result_val))); r_p= &mut r_p.as_mut().unwrap().next; n2_p=&n2_p.as_ref().unwrap().next; } if carry != 0 { r_p.as_mut().unwrap().next = Some(Box::new(ListNode::new(carry))); r_p= &mut r_p.as_mut().unwrap().next; } result_dummy_head.unwrap().next } }