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;
    }
}
原文地址:https://www.cnblogs.com/mapoos/p/13942156.html