AddTwoNumber2 两数之和
2020-04-15 21:36 tonyniu8 阅读(193) 评论(0) 编辑 收藏 举报- 两数相加 II
给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
进阶:
如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。
示例:
输入:(7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 8 -> 0 -> 7
// 因为是逆序想到要用栈,
// 1.先用两个栈,然后pop出来。
// 2.然后用一个链表
// 链表时要两个节点, 一个为res, 一个为curr
// public E peek()
//// Looks at the object at the top of this stack without removing it from the stack.
// 如果为空则会报 EmptyStackException - if this stack is empty.
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
Stack<Integer> s1 = new Stack<>();
Stack<Integer> s2 = new Stack<>();
while (l1 != null) {
s1.push(l1.val);
l1 = l1.next;
}
while (l2 != null) {
s2.push(l2.val);
l2 = l2.next;
}
int carry = 0;
ListNode res= null ;
while (!s1.empty() || !s2.empty() || carry != 0) {
int i1 = s1.empty() ? 0 : s1.pop();
int i2 = s2.empty() ? 0 : s2.pop();
int sum = i1 + i2 + carry;
ListNode n = new ListNode(sum % 10);
carry = sum / 10;
n.next = res;
res = n;
}
return res;
}