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
給定兩個用鏈表表示的整數(shù),計算它們的和并同樣用鏈表表示。
不逆序鏈表的話,可以用棧處理。
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = null;
Deque<Integer> A = new ArrayDeque<>();
Deque<Integer> B = new ArrayDeque<>();
int carry = 0;
while (l1 != null) {
A.push(l1.val);
l1 = l1.next;
}
while (l2 != null) {
B.push(l2.val);
l2 = l2.next;
}
while (!A.isEmpty() || !B.isEmpty()) {
int a = A.isEmpty() ? 0 : A.pop();
int b = B.isEmpty() ? 0 : B.pop();
int sum = a + b + carry;
carry = sum / 10;
sum = sum % 10;
head = new ListNode(sum, head);
}
if (carry > 0) {
head = new ListNode(carry, head);
}
return head;
}
}