YSMull
<-- algorithm



原题链接

如果允许修改链表,就分别反转后相加,再反转。
题目不允许修改链表,就是用栈来做。

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        LinkedList<Integer> stack1 = new LinkedList<>();
        LinkedList<Integer> stack2 = new LinkedList<>();
        while (l1 != null) {
            stack1.push(l1.val);
            l1 = l1.next;
        }
        while (l2 != null) {
            stack2.push(l2.val);
            l2 = l2.next;
        }
        ListNode head = null;
        int c = 0;
        while (!stack1.isEmpty() || !stack2.isEmpty() || c != 0) {
            int a = stack1.isEmpty() ? 0 : stack1.pop();
            int b = stack2.isEmpty() ? 0 : stack2.pop();
            int s = (a + b + c) % 10;
            c = (a + b + c) / 10;
            ListNode node = new ListNode(s);
            node.next = head;
            head = node;
        }
        return head;
    }
}