-
-
Notifications
You must be signed in to change notification settings - Fork 8.5k
/
Copy pathSolution.java
31 lines (31 loc) · 976 Bytes
/
Solution.java
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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
Deque<Integer> s1 = new ArrayDeque<>();
Deque<Integer> s2 = new ArrayDeque<>();
for (; l1 != null; l1 = l1.next) {
s1.push(l1.val);
}
for (; l2 != null; l2 = l2.next) {
s2.push(l2.val);
}
int carry = 0;
ListNode dummy = new ListNode();
while (!s1.isEmpty() || !s2.isEmpty() || carry != 0) {
carry += (s1.isEmpty() ? 0 : s1.pop()) + (s2.isEmpty() ? 0 : s2.pop());
ListNode node = new ListNode(carry % 10, dummy.next);
dummy.next = node;
carry /= 10;
}
return dummy.next;
}
}