LeetCode-2. Add Two Numbers(鏈表實(shí)現(xiàn)數(shù)字相加)

1.題目描述

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

2.我的分析思路

拿到題目,我的第一個(gè)思路是這樣的:

兩個(gè)鏈表,當(dāng)鏈表均不為空時(shí),將鏈表push到棧中,然后同時(shí)pop出來,計(jì)算棧中數(shù)字之和;計(jì)算完成后,判斷將和對(duì)10求余數(shù),放到結(jié)果的頭結(jié)點(diǎn)中,然后把商push到棧中,然后將原始兩個(gè)鏈表的值的next賦值為原來的兩個(gè)鏈表。

如此遞歸,即可求出最終值。

不過這里面的判斷方式有些問題,比如遞歸的條件,應(yīng)該是棧不為空,或者原始的兩個(gè)鏈表不為空。

寫的代碼比較冗余,就不獻(xiàn)丑了。

3.其他的思路

現(xiàn)在貼出贊比較多的一個(gè)解。

public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode prev = new ListNode(0);
    ListNode head = prev;
    int carry = 0;
    while (l1 != null || l2 != null || carry != 0) {
        ListNode cur = new ListNode(0);
        int sum = ((l2 == null) ? 0 : l2.val) + ((l1 == null) ? 0 : l1.val) + carry;
        cur.val = sum % 10;
        carry = sum / 10;
        prev.next = cur;
        prev = cur;
        l1 = (l1 == null) ? l1 : l1.next;
        l2 = (l2 == null) ? l2 : l2.next;
    }
    return head.next;
}

這里沒有使用到棧的概念,增加了一個(gè)carry,也就是表示商。同時(shí),這里面有個(gè)概念,java到底是傳值和傳引用,這里的head和prev就是這樣。

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

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

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