LeetCode-445. 两数相加 II
题目来源
题目详情
给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 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
进阶: 如果输入链表不能翻转该如何解决?
题解分析
解法一:链表翻转
/**
* 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) {
l1 = reverseList(l1);
l2 = reverseList(l2);
ListNode newHead = addTwoList(l1, l2);
return reverseList(newHead);
}
private ListNode reverseList(ListNode head){
ListNode now = head, pre = null;
while(now != null){
ListNode next = now.next;
now.next = pre;
pre = now;
now = next;
}
return pre;
}
private ListNode addTwoList(ListNode list1, ListNode list2){
ListNode dumyNode = new ListNode(-1);
ListNode now = dumyNode;
int carry = 0;
while(carry != 0 || list1 != null || list2 != null){
int a = 0, b = 0;
if(list1 != null){
a = list1.val;
list1 = list1.next;
}
if(list2 != null){
b = list2.val;
list2 = list2.next;
}
int sum = carry + a + b;
carry = sum / 10;
now.next = new ListNode(sum % 10);
now = now.next;
}
now.next = null;
return dumyNode.next;
}
}
解法二:栈
- 本题的要求里需要不能翻转原先的两个链表来实现链表的加法,考虑到链表的特性,这里考虑使用栈来求解。
- 栈的特点就是先进后出,所以我们可以先把所有元素分别进栈,然后依次出栈相加,与此同时构造出新的ListNode,将其接到head节点的后面。
/**
* 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) {
LinkedList<Integer> sta1 = new LinkedList<>();
LinkedList<Integer> sta2 = new LinkedList<>();
while(l1 != null){
sta1.push(l1.val);
l1 = l1.next;
}
while(l2 != null){
sta2.push(l2.val);
l2 = l2.next;
}
ListNode dumyNode = new ListNode(-1);
ListNode now = dumyNode;
int carry = 0;
while(carry != 0 || !sta1.isEmpty() || !sta2.isEmpty()){
int a = 0, b = 0;
if(!sta1.isEmpty()){
a = sta1.pop();
}
if(!sta2.isEmpty()){
b = sta2.pop();
}
int sum = carry + a + b;
carry = sum / 10;
ListNode temp = new ListNode(sum % 10);
ListNode next = now.next;
temp.next = next;
now.next = temp;
}
return dumyNode.next;
}
}
Either Excellent or Rusty