打开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

题意

给定两个用链表表示的整数,计算它们的和并同样用链表表示。

思路

不逆序链表的话,可以用栈处理。


代码实现

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;
    }
}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
355,两数相加 II
​LeetCode刷题实战369:给单链表加一
2 Add Two Numbers
0142. Linked List Cycle II (M)
LeetCode 142.环形链表II
142. 环形链表 II
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服