445.两数相加

给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。

你可以假设除了数字 0 之外,这两个数字都不会以零开头。

进阶:

如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
     
    private ListNode head = new ListNode(0);

    private void addNode(Integer val){
        ListNode node;
        if (head.val + val >= 10){
            head.val += val - 10;
            node = new ListNode(1);

        }else {
            head.val += val;
            node = new ListNode(0);
        }
        node.next = head;
        head = node;
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1.val == 0){
            return l2;
        }
        if (l2.val == 0){
            return l1;
        }
        Stack<Integer> stack1 = new Stack<>();
        Stack<Integer> stack2 = new Stack<>();

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

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

        while (!stack1.isEmpty() && !stack2.isEmpty()){
            Integer pop1 = stack1.pop();
            Integer pop2 = stack2.pop();
            addNode(pop1+pop2);
        }
        
        while (!stack1.isEmpty()){
            addNode(stack1.pop());
        }

        while (!stack2.isEmpty()){
            addNode(stack2.pop());
        }

        if (head.val == 0){
            head = head.next;
        }
        return head;
    }
}
原文地址:https://www.cnblogs.com/yinqs/p/12783878.html