LeetCode 兩數(shù)相加 Rust

LeetCode 兩數(shù)相加 Rust

題目

給出兩個非空的鏈表用來表示兩個非負(fù)的整數(shù)。其中,它們各自的位數(shù)是按照 逆序 的方式存儲的,并且它們的每個節(jié)點只能存儲 一位 數(shù)字。如果,我們將這兩個數(shù)相加起來,則會返回一個新的鏈表來表示它們的和。您可以假設(shè)除了數(shù)字 0 之外,這兩個數(shù)都不會以 0 開頭。

  • 在Rust代碼中主要考慮Option的操作,對Option的引用或者M(jìn)ove。Rust中任何資源都是有持有者的,也就是ownership。
    在本例中Option持有了他內(nèi)部的None或者Some(x),一旦解開這個Option,那么Option結(jié)構(gòu)就會在scope結(jié)束后被釋放。
    針對這種情況Rust提供了as_mut, as_ref兩個接口來獲取Option內(nèi)部資源的引用。從而避免解開Option包裹后發(fā)生所有權(quán)轉(zhuǎn)移。

  • Rust中不是使用* int 類型申明指針,而是使用 let x: &i32 = &y 這樣的形式申明指針。

  • 對指針的解引用概念與C/C++是一致的,用法類似二級指針。
    本例中l(wèi)et mut cur = &mut head.next;cur是一個指向head.next的指針,對cur進(jìn)行解引用,則代表對head.next賦值。
    對cur進(jìn)行賦值后,則可以正常的移動指針,即:cur = &mut cur.as_mut().unwrap().next;

  • 代碼中有重復(fù)內(nèi)容,使用函數(shù)閉包來封裝處理過程,是較為簡潔的做法。


#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ListNode {
    pub val: i32,
    pub next: Option<Box<ListNode>>,
}

impl ListNode {
    #[inline]
    fn new(val: i32) -> Self {
        ListNode { next: None, val }
    }
}
struct Solution;
impl Solution {
    pub fn add_two_numbers(
        l1: Option<Box<ListNode>>,
        l2: Option<Box<ListNode>>,
    ) -> Option<Box<ListNode>> {

        let mut head = ListNode::new(0);
        let mut cur = &mut head.next;
        let (mut x, mut y) = (l1, l2);
        let mut upper = 0;
        let node_val = |node: &Option<Box<ListNode>>| node.as_ref().map_or(0, |x| x.val);
        let node_next = |node: Option<Box<ListNode>>| node.map_or(None, |node| node.next);
        while x.is_some() || y.is_some() || upper == 1 {
            let sum = node_val(&x) + node_val(&y) + upper;
            upper = 0;
            if sum >= 10 {
                upper = 1;
            }
            let node = ListNode::new(sum % 10);
            *cur = Some(Box::new(node));
            cur = &mut cur.as_mut().unwrap().next;
            x = node_next(x);
            y = node_next(y);
        }
        return head.next;
    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容