-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmedium_445_AddTwoNumbersII.java
More file actions
40 lines (36 loc) · 949 Bytes
/
medium_445_AddTwoNumbersII.java
File metadata and controls
40 lines (36 loc) · 949 Bytes
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
import java.util.Stack;
/**
* created by zl on 2019/5/15 20:27
*/
public class medium_445_AddTwoNumbersII {
public ListNode addTwoNumbers(ListNode l1, ListNode l2)
{
Stack<Integer> s1 = new Stack<Integer>();
Stack<Integer> s2 = new Stack<Integer>();
while(l1 != null)
{
s1.push(l1.val);
l1 = l1.next;
}
while(l2 != null)
{
s2.push(l2.val);
l2 = l2.next;
}
int sum = 0;
ListNode list = new ListNode(0);
while (!s1.empty() || !s2.empty())
{
if (!s1.empty())
sum += s1.pop();
if (!s2.empty())
sum += s2.pop();
list.val = sum % 10;
ListNode head = new ListNode(sum/10);
head.next = list;
list = head;
sum /= 10;
}
return list.val == 0 ? list.next : list;
}
}