免费视频淫片aa毛片_日韩高清在线亚洲专区vr_日韩大片免费观看视频播放_亚洲欧美国产精品完整版

打開APP
userphoto
未登錄

開通VIP,暢享免費電子書等14項超值服

開通VIP
0445. Add Two Numbers II (M)

Add Two Numbers II (M)

題目

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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.

Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.

Example:

Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7

題意

給定兩個用鏈表表示的整數(shù),計算它們的和并同樣用鏈表表示。

思路

不逆序鏈表的話,可以用棧處理。


代碼實現(xiàn)

Java


class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = null;
        Deque<Integer> A = new ArrayDeque<>();
        Deque<Integer> B = new ArrayDeque<>();
        int carry = 0;

        while (l1 != null) {
            A.push(l1.val);
            l1 = l1.next;
        }
        while (l2 != null) {
            B.push(l2.val);
            l2 = l2.next;
        }

        while (!A.isEmpty() || !B.isEmpty()) {
            int a = A.isEmpty() ? 0 : A.pop();
            int b = B.isEmpty() ? 0 : B.pop();
            int sum = a + b + carry;
            carry = sum / 10;
            sum = sum % 10;
            head = new ListNode(sum, head);
        }

        if (carry > 0) {
            head = new ListNode(carry, head);
        }

        return head;
    }
}
本站僅提供存儲服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊舉報。
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
355,兩數(shù)相加 II
?LeetCode刷題實戰(zhàn)369:給單鏈表加一
2 Add Two Numbers
0142. Linked List Cycle II (M)
LeetCode 142.環(huán)形鏈表II
142. 環(huán)形鏈表 II
更多類似文章 >>
生活服務(wù)
分享 收藏 導(dǎo)長圖 關(guān)注 下載文章
綁定賬號成功
后續(xù)可登錄賬號暢享VIP特權(quán)!
如果VIP功能使用有故障,
可點擊這里聯(lián)系客服!

聯(lián)系客服