[LeetCode] 445. 两数相加 II

链表形式的大数相加,没什么难的

题目要求不能修改原链表。那就把两个链表遍历一遍,把数取出来放到stack里,再进行相加

或者利用递归?(不过也是一样的,自己构建的栈只是换成了递归栈)

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        Stack<Integer> a = new Stack<>();
        Stack<Integer> b = new Stack<>();

        while (l1 != null) {
            a.push(l1.val);
            l1 = l1.next;
        }

        while (l2 != null) {
            b.push(l2.val);
            l2 = l2.next;
        }

        ListNode last = new ListNode();
        ListNode head = null;
        int c = 0;
        while (!a.empty()&&!b.empty()) {
            last.val = (c + a.peek() + b.peek()) % 10;
            c = (c + a.peek() + b.peek()) / 10;

            head = new ListNode();
            head.next = last;
            last = head;

            a.pop();
            b.pop();
        }

        while (!a.empty()) {
            last.val = (c + a.peek()) % 10;
            c = (c + a.peek()) / 10;

            head = new ListNode();
            head.next = last;
            last = head;

            a.pop();
        }

        while (!b.empty()) {
            last.val = (c + b.peek()) % 10;
            c = (c + b.peek()) / 10;

            head = new ListNode();
            head.next = last;
            last = head;

            b.pop();
        }

        if (c != 0) {
            last.val = c;
            head = new ListNode();
            head.next = last;
        }

        return head.next;
    }
}
posted @ 2021-06-15 12:29  ACBingo  阅读(18)  评论(0编辑  收藏  举报