首页 > 试题广场 >

链表相加(一)

[编程题]链表相加(一)
  • 热度指数:1590 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定两个非空链表逆序存储的的非负整数,每个节点只存储一位数组。
请你把两个链表相加以下相同方法返回链表,保证两个数都不会以 0 开头。
数据范围: ,每个节点的值都满足
示例1

输入

{2,5,6},{5,6,1}

输出

{7,1,8}
示例2

输入

{0},{1,2,3,4,5,6}

输出

{1,2,3,4,5,6}
示例3

输入

{9,9,9},{9,9,0}

输出

{8,9,0,1}

说明:本题目包含复杂数据结构ListNode,点此查看相关信息
/**
 *  #[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
    }
}

发表于 2023-08-17 18:47:49 回复(0)