Skip to content

Commit 43cd3c3

Browse files
authored
Create Solution.java
1 parent e5e7836 commit 43cd3c3

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution {
2+
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
3+
Deque<Integer> s1 = new ArrayDeque<>();
4+
Deque<Integer> s2 = new ArrayDeque<>();
5+
for (; l1 != null; l1 = l1.next) {
6+
s1.push(l1.val);
7+
}
8+
for (; l2 != null; l2 = l2.next) {
9+
s2.push(l2.val);
10+
}
11+
ListNode head = null;
12+
int carry = 0;
13+
while (!s1.isEmpty() || !s2.isEmpty() || carry > 0) {
14+
carry += (s1.isEmpty() ? 0 : s1.pop()) + (s2.isEmpty() ? 0 : s2.pop());
15+
ListNode h = new ListNode(carry % 10);
16+
h.next = head;
17+
head = h;
18+
carry /= 10;
19+
}
20+
return head;
21+
}
22+
}

0 commit comments

Comments
 (0)