LeetCode 445. 两数相加 II(Add Two Numbers II)

时间:2023-09-23 15:41:20

445. 两数相加 II

445. Add Two Numbers II

题目描述

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

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

进阶:

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

LeetCode445. Add Two Numbers II中等

示例:

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

Java 实现

public class ListNode {
int val;
ListNode next; ListNode(int x) {
val = x;
} @Override
public String toString() {
return val + "->" + next;
}
}
import java.util.Stack;

class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
Stack<Integer> s1 = new Stack<Integer>();
Stack<Integer> s2 = new Stack<Integer>(); while (l1 != null) {
s1.push(l1.val);
l1 = l1.next;
}
while (l2 != null) {
s2.push(l2.val);
l2 = l2.next;
} int sum = 0;
ListNode list = new ListNode(0);
while (!s1.empty() || !s2.empty()) {
if (!s1.empty()) sum += s1.pop();
if (!s2.empty()) sum += s2.pop();
list.val = sum % 10;
ListNode head = new ListNode(sum / 10);
head.next = list;
list = head;
sum /= 10;
}
return list.val == 0 ? list.next : list;
}
}

测试代码

import java.util.Stack;

class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
Stack<Integer> s1 = new Stack<Integer>();
Stack<Integer> s2 = new Stack<Integer>(); while (l1 != null) {
s1.push(l1.val);
l1 = l1.next;
}
while (l2 != null) {
s2.push(l2.val);
l2 = l2.next;
} int sum = 0;
ListNode list = new ListNode(0);
while (!s1.empty() || !s2.empty()) {
if (!s1.empty()) sum += s1.pop();
if (!s2.empty()) sum += s2.pop();
list.val = sum % 10;
ListNode head = new ListNode(sum / 10);
head.next = list;
list = head;
sum /= 10;
System.out.println(list);
}
return list.val == 0 ? list.next : list;
} public static void main(String[] args) {
ListNode t1 = new ListNode(7);
ListNode t2 = new ListNode(2);
ListNode t3 = new ListNode(4);
ListNode t4 = new ListNode(3);
t1.next = t2;
t2.next = t3;
t3.next = t4; ListNode p1 = new ListNode(5);
ListNode p2 = new ListNode(6);
ListNode p3 = new ListNode(4);
p1.next = p2;
p2.next = p3; System.out.println(new Solution().addTwoNumbers(t1, p1));
}
}

测试结果

0->7->null
1->0->7->null
0->8->0->7->null
0->7->8->0->7->null
7->8->0->7->null

相似题目

参考资料