-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path445. Add Two Numbers II
56 lines (38 loc) · 1.37 KB
/
445. Add Two Numbers II
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
49
50
51
52
53
54
55
56
/**Runtime: 3 ms, faster than 63.11% of Java online submissions for Add Two Numbers II.
Memory Usage: 39 MB, less than 90.46% of Java online submissions for Add Two Numbers II.
* 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) {
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 sum=0;
ListNode result= new ListNode(0) ;
while( !stack1.empty() || !stack2.empty() )
{
if(!stack1.empty()) sum+=stack1.pop();
if(!stack2.empty()) sum+=stack2.pop();
result.val=sum%10;
ListNode head= new ListNode(sum/10);
head.next=result;
result =head;
sum/=10;
}
return result.val == 0 ? result.next : result;
}
}