LeetCode 445.两数相加 II

题目传送门:两数相加 II


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

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

要求:不能修改原始链表。

示例:

输入:(7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 8 -> 0 -> 7

因为我们把链表的每一位相加与我们遍历链表的顺序是相反的,我们可以借助栈来解决问题。

时间复杂度:O(max(m,n)),其中 m 与 n 分别为两个链表的长度。我们需要遍历每个链表。

空间复杂度:O(m+n),其中 m 与 n 分别为两个链表的长度。这是我们把链表内容放入栈中所用的空间。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        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;
        }

        int carry = 0;
        ListNode head = null;
        while(!stack1.isEmpty() || !stack2.isEmpty() || carry > 0) {
            int sum = carry;
            sum += stack1.isEmpty()? 0:stack1.pop();
            sum += stack2.isEmpty()? 0:stack2.pop();
            ListNode node = new ListNode(sum % 10); // sum操作就是为了保留这个节点个位数的值

            //下面两步操作为头插法创建链表
            node.next = head;
            head = node;

            //判断是否有进位,如果有进位的话下一次sum的值就为1
            carry = sum / 10;
        }
        return head;
    }
}
如果博客内容有误,请联系我修改指正,非常感谢! 如果觉得这篇博客对你有用的话,就帮我点个小小的赞吧! 一起加油鸭, 越努力,越幸运!!!
原文地址:https://www.cnblogs.com/studywithme/p/13556506.html