-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddTwoNumbersII.java
More file actions
48 lines (44 loc) · 1.13 KB
/
Copy pathAddTwoNumbersII.java
File metadata and controls
48 lines (44 loc) · 1.13 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import java.util.Stack;
public class AddTwoNumbersII {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
while(l1 != null){
stack1.push(l1.val);
l1 = l1.next;
}
while(l2 != null){
stack2.push(l2.val);
l2 = l2.next;
}
int carry = 0;
ListNode l3 = new ListNode(0);
while(!stack1.isEmpty() || !stack2.isEmpty()){
int sum = (stack1.isEmpty() ? 0 : stack1.pop()) + (stack2.isEmpty() ? 0 : stack2.pop()) + carry;
carry = sum / 10;
ListNode node = new ListNode(sum % 10);
ListNode temp = l3.next;
l3.next = node;
l3.next.next = temp;
}
if(carry > 0){
ListNode node = new ListNode(carry);
ListNode temp = l3.next;
l3.next = node;
l3.next.next = temp;
}
return l3.next;
}
public static void main(String[] args) {
AddTwoNumbersII add = new AddTwoNumbersII();
ListNode l1 = new ListNode(6);
ListNode l2 = new ListNode(9);
ListNode l3 = new ListNode(4);
l2.next = l3;
ListNode res = add.addTwoNumbers(l1, l2);
while(res != null){
System.out.print(res.val + " ");
res = res.next;
}
}
}