445. 两数相加 II

310 阅读1分钟

题目介绍

力扣445题:leetcode-cn.com/problems/ad…

image.png

image.png

分析

改题目与[2. 两数相加]类似,本题的主要难点在于链表中数位的顺序与我们做加法的顺序是相反的,为了逆序处理所有数位,我们可以使用栈:把所有数字压入栈中,再依次取出相加。计算过程中需要注意进位的情况。

我们需要构建两个栈,将两个链表中的值分别压入这两个栈中。

image.png

每次都从两个栈中各弹出一个元素,就是我们所需要的最末位元素,按照计算方式,相加取模求当前位的值,同时我们还需要记录当前位的进位。最后,我们使用获得的值,构建一个节点。

image.png

我们需要使用一个指针作为头指针,指向当前节点。每次新增节点,我们只需要将新节点插入到头指针之后即可。

image.png

代码如下:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        Stack<ListNode> stack1 = new Stack<>();
        Stack<ListNode> stack2 = new Stack<>();
        while(l1 != null) {
            stack1.push(l1);
            l1 = l1.next;
        }
        while(l2 != null) {
            stack2.push(l2);
            l2 = l2.next;
        }
        ListNode pre = null;
        int carry = 0;//存储进位
        while((!stack1.isEmpty()) || (!stack2.isEmpty()) || carry > 0) {
            int l1Val = stack1.isEmpty() ? 0 : stack1.pop().val;
            int l2Val = stack2.isEmpty() ? 0 : stack2.pop().val;
            int sum = l1Val + l2Val + carry;
            carry = sum / 10;//进位值
            sum = sum % 10;
            ListNode cur = new ListNode(sum);
            //进行反转
            cur.next = pre;
            pre = cur;
        } 
        return pre;
    }
}

复杂度分析

  • 时间复杂度:O(max(m, n)),其中 m 和 n 分别为两个链表的长度。我们需要遍历两个链表的全部位置,而处理每个位置只需要 O(1) 的时间。

  • 空间复杂度:O(m + n),其中 m 和 n 分别为两个链表的长度。空间复杂度主要取决于我们把链表内容放入栈中所用的空间。