Add Two Numbers II
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7Basic Idea:
Java Code:
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
// 把两个list的数字放入stack,这样pop的顺序就是低位到高位
Deque<Integer> stack1 = new LinkedList<>();
Deque<Integer> stack2 = new LinkedList<>();
while (l1 != null) {
stack1.addFirst(l1.val);
l1 = l1.next;
}
while (l2 != null) {
stack2.addFirst(l2.val);
l2 = l2.next;
}
// 一次按位相加,存carrier,结果直接append到return list的左边
ListNode dummy = new ListNode(0);
int carrier = 0;
while (! stack1.isEmpty() || ! stack2.isEmpty() || carrier != 0) {
int adder1 = stack1.isEmpty() ? 0 : stack1.removeFirst();
int adder2 = stack2.isEmpty() ? 0 : stack2.removeFirst();
int res = adder1 + adder2 + carrier;
int num = res % 10;
carrier = res / 10;
ListNode curr = new ListNode(num);
curr.next = dummy.next;
dummy.next = curr;
}
return dummy.next;
}
}