用 Rust 刷 leetcode 第二題

linghuyichong發表於2019-12-05

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.

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

Output: 7 -> 0 -> 8

Explanation: 342 + 465 = 807.

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 協議》,轉載必須註明作者和本文連結
令狐一衝

相關文章