用 Rust 刷 leetcode 第二题

Problem

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)

Output: 7 -> 0 -> 8

Explanation: 342 + 465 = 807.

Solution

pub fn reverse_list(node: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
    let mut s = node;
    let mut e = None;
    while let Some(mut n) = s.take() {
        s = n.next;
        n.next = e;
        e = Some(n);
    } 
    e
}

impl Solution {
    pub fn add_two_numbers(l1: Option<Box<ListNode>>, l2: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
        let mut l1_curr = l1;
        let mut l2_curr = l2;
        let mut carry = 0;
        let mut result = None;
        while l1_curr.is_some() || l2_curr.is_some() || carry > 0{
            let mut sum = carry;
            if let Some(n) = l1_curr {
                sum += n.val;
                l1_curr = n.next;
            }
            if let Some(n) = l2_curr {
                sum += n.val;
                l2_curr = n.next;
            }
            carry = sum/10;
            let mut node = ListNode::new(sum%10);
            node.next = result;
            result = Some(Box::new(node));
        }
        reverse_list(result)
    }
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
令狐一冲
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
文章
255
粉丝
120
喜欢
308
收藏
128
排名:335
访问:2.8 万
私信
所有博文
社区赞助商