leetcode 445题:两数相加Ⅱ
给定两个非空链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储单个数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
进阶:
如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。
示例:
输入: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
输出: 7 -> 8 -> 0 -> 7
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:
将两个链表压入两个栈,从栈首取数字相加压入结果栈,保留进位,某一个栈空将另一个栈全部压入结果栈。需要注意最后进位不为 0时,需要压一个1入结果栈。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
import java.util.Stack;
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
Stack<Integer> op1Stack = new Stack<>();
Stack<Integer> op2Stack = new Stack<>();
Stack<Integer> resultStack = new Stack<>();
int add = 0;
while (l1 != null) {
op1Stack.push(l1.val);
l1 = l1.next;
}
while (l2 != null) {
op2Stack.push(l2.val);
l2 = l2.next;
}
while (!op1Stack.isEmpty() | !op2Stack.isEmpty()) {
if (op2Stack.isEmpty()) {
while (!op1Stack.isEmpty()) {
int cur = op1Stack.pop();
resultStack.push((cur + add) % 10);
if (cur + add > 9) {
add = 1;
} else {
add = 0;
}
}
} else if (op1Stack.isEmpty()) {
while (!op2Stack.isEmpty()) {
int cur = op2Stack.pop();
resultStack.push((cur + add) % 10);
if (cur + add > 9) {
add = 1;
} else {
add = 0;
}
}
} else {
int op1 = op1Stack.pop();
int op2 = op2Stack.pop();
int sum = op1 + op2;
resultStack.push((sum + add) % 10);
if (sum + add > 9) {
add = 1;
} else {
add = 0;
}
}
}
if (add != 0) {
resultStack.push(add);
}
ListNode head = new ListNode(resultStack.pop());
ListNode pNode = head;
while (!resultStack.isEmpty()) {
ListNode node = new ListNode(resultStack.pop());
pNode.next = node;
pNode = node;
}
return head;
}
}