445. 两数相加 IIhttps://leetcode.cn/problems/add-two-numbers-ii/
难度中等550
给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 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) {
Stack<ListNode> stack1 = new Stack<ListNode>();
Stack<ListNode> stack2 = new Stack<ListNode>();
ListNode head = new ListNode();
int n = 0;
while(l1!=null)
{
stack1.push(l1);
l1 = l1.next;
}
while(l2!=null)
{
stack2.push(l2);
l2 = l2.next;
}
ListNode a = null;
ListNode b = null;
while(!stack1.isEmpty() && !stack2.isEmpty())
{
a = stack1.pop();
b = stack2.pop();
int x = (b.val+a.val+n);
n = x/10;
a.val = x%10;
a.next = head.next;
head.next = a;
a = head.next;
}
while(!stack1.isEmpty())
{
a =stack1.pop();
int x = a.val+n;
n = x/10;
a.val = x%10;
a.next = head.next;
head.next = a;
a = head.next;
}
while(!stack2.isEmpty())
{
a =stack2.pop();
int x = a.val+n;
n = x/10;
a.val = x%10;
a.next = head.next;
head.next = a;
a = head.next;
}
if(n!=0)
{
head.val = n;
return head;
}
return head.next;
}
}