forked from szl0072/Leetcode-Solution-Code
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAddTwoNumbersII.java
56 lines (48 loc) · 1.24 KB
/
AddTwoNumbersII.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
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
package leetcode;
import java.util.List;
import java.util.Stack;
/**
* Project Name : Leetcode
* Package Name : leetcode
* File Name : AddTwoNumbersII
* Creator : Edward
* Date : Sep, 2017
* Description : 445. Add Two Numbers II
*/
public class AddTwoNumbersII {
/**
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7
time : O(n)
space : O(n)
解法1 : Stack
解法2 : Reverse
* @param l1
* @param l2
* @return
*/
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
Stack<Integer> s1 = new Stack<>();
Stack<Integer> s2 = new Stack<>();
while (l1 != null) {
s1.push(l1.val);
l1 = l1.next;
}
while (l2 != null) {
s2.push(l2.val);
l2 = l2.next;
}
ListNode cur = new ListNode(0);
int sum = 0;
while (!s1.isEmpty() || !s2.isEmpty()) {
if (!s1.isEmpty()) sum += s1.pop();
if (!s2.isEmpty()) sum += s2.pop();
cur.val = sum % 10;
ListNode head = new ListNode(sum / 10);
head.next = cur;
cur = head;
sum /= 10;
}
return cur.val == 0 ? cur.next : cur;
}
}