加载中...
445-两数相加 II(Add Two Numbers II)
发表于:2021-12-03 | 分类: 中等
字数统计: 450 | 阅读时长: 2分钟 | 阅读量:

原文链接: https://leetcode-cn.com/problems/add-two-numbers-ii

英文原文

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

 

Example 1:

Input: l1 = [7,2,4,3], l2 = [5,6,4]
Output: [7,8,0,7]

Example 2:

Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [8,0,7]

Example 3:

Input: l1 = [0], l2 = [0]
Output: [0]

 

Constraints:

  • The number of nodes in each linked list is in the range [1, 100].
  • 0 <= Node.val <= 9
  • It is guaranteed that the list represents a number that does not have leading zeros.

 

Follow up: Could you solve it without reversing the input lists?

中文题目

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

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

 

示例1:

输入:l1 = [7,2,4,3], l2 = [5,6,4]
输出:[7,8,0,7]

示例2:

输入:l1 = [2,4,3], l2 = [5,6,4]
输出:[8,0,7]

示例3:

输入:l1 = [0], l2 = [0]
输出:[0]

 

提示:

  • 链表的长度范围为 [1, 100]
  • 0 <= node.val <= 9
  • 输入数据保证链表代表的数字无前导 0

 

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

通过代码

高赞题解

🙋‍♀️就喜欢这种短短的打卡题,短短的打个卡,短短的发个题解,哎又是美妙的夜晚!

update:统一回复下头插法的评论,不熟悉的可以用迭代法去做做 206. 反转链表,需要链表逆序的时候就用头插法。

用 stack 保存链表,再从 stack 中取出来,就是数字从低位到高位访问了。

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);
            node.next = head;
            head = node;
            carry = sum / 10;
        }
        return head;
    }
}

统计信息

通过次数 提交次数 AC比率
86395 146412 59.0%

提交历史

提交时间 提交结果 执行时间 内存消耗 语言

相似题目

题目 难度
两数相加 中等
上一篇:
443-压缩字符串(String Compression)
下一篇:
446-等差数列划分 II - 子序列(Arithmetic Slices II - Subsequence)
本文目录
本文目录