题目
给你两个非空链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。
示例:
输入:(7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 8 -> 0 -> 7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
| /**
* 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) {
ListNode result = null;
Deque<Integer> s1 = new LinkedList<>();
Deque<Integer> s2 = new LinkedList<>();
while (l1 != null) {
s1.push(l1.val);
l1 = l1.next;
}
while (l2 != null) {
s2.push(l2.val);
l2 = l2.next;
}
int carry = 0;
while (!s1.isEmpty() || !s2.isEmpty() || carry > 0){
int sum = carry;
sum += s1.isEmpty()?0:s1.pop();
sum += s2.isEmpty()?0:s2.pop();
carry = sum / 10;
ListNode node = new ListNode(sum % 10);
node.next = result;
result = node;
}
return result;
}
}
|