Medium
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Example:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7
這道題看的答案,一旦理解可謂相當簡單,頓時變Easy. 這里要用到三個棧, s1, s2來壓鏈表節(jié)點,res來壓求和鏈表。 注意一下每次運算得到的進位carry, 這個進位是下一次循環(huán)更低位求和運算時才會用到的。 而digit則是每次運算后該位上的數字,也就是我們要壓進res里的節(jié)點val.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1 == null && l2 == null){
return null;
}
if (l1 == null || l2 == null){
return l1 == null ? l2 : l1;
}
Stack<ListNode> s1 = new Stack<>();
Stack<ListNode> s2 = new Stack<>();
Stack<ListNode> res = new Stack<>();
while (l1 != null){
s1.push(l1);
l1 = l1.next;
}
while (l2 != null){
s2.push(l2);
l2 = l2.next;
}
int carry = 0;
while (!s1.isEmpty() || !s2.isEmpty()){
int sum = 0;
if (!s1.isEmpty() && !s2.isEmpty()){
sum += s1.pop().val + s2.pop().val;
} else if (!s1.isEmpty()){
sum += s1.pop().val;
} else if (!s2.isEmpty()){
sum += s2.pop().val;
}
//here, carry is from last loop.
int digit = (sum + carry) % 10;
carry = (sum + carry) / 10;
res.push(new ListNode(digit));
}
if (carry == 1){
res.push(new ListNode(carry));
}
ListNode dummy = new ListNode(-1);
ListNode node = dummy;
while (!res.isEmpty()){
node.next = res.pop();
node = node.next;
}
return dummy.next;
}
}