-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMain25.java
More file actions
82 lines (77 loc) · 2.29 KB
/
Main25.java
File metadata and controls
82 lines (77 loc) · 2.29 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package JZOfferTuJi;
import java.util.ArrayDeque;
import java.util.Deque;
/**
* 反转链表方法
*/
public class Main25 {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
l1 = reverseNode(l1);
l2 = reverseNode(l2);
int carry = 0;
ListNode dummyNode = new ListNode(-1);
ListNode head = dummyNode;
while (l1 != null || l2 != null || carry != 0){
int a = l1 != null ? l1.val : 0;
int b = l2 != null ? l2.val : 0;
ListNode tmp = new ListNode((a + b + carry) % 10);
carry = (a + b + carry) / 10;
head.next = tmp;
head = head.next;
l1 = l1 != null ? l1.next : null;
l2 = l2 != null ? l2.next : null;
}
return reverseNode(dummyNode.next);
}
private ListNode reverseNode(ListNode head) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
while (head.next != null){
ListNode next = head.next;
head.next = next.next;
next.next = dummy.next;
dummy.next = next;
}
return dummy.next;
}
private ListNode reverseNode1(ListNode head) {
ListNode cur = null;
while (head != null) {
ListNode tmp = head;
head = head.next;
tmp.next = cur;
cur = tmp;
}
return cur;
}
}
/**
* 栈
*/
class Main25_1 {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
Deque<Integer> stack1 = new ArrayDeque<>();
Deque<Integer> stack2 = new ArrayDeque<>();
while (l1 != null) {
stack1.push(l1.val);
l1 = l1.next;
}
while (l2 != null) {
stack2.push(l2.val);
l2 = l2.next;
}
ListNode dummy = new ListNode(-1);
ListNode cur = null;
int carry = 0;
while (!stack1.isEmpty() || !stack2.isEmpty() || carry != 0) {
int a = !stack1.isEmpty() ? stack1.pollFirst() : 0;
int b = !stack2.isEmpty() ? stack2.pollFirst() : 0;
ListNode tmp = new ListNode((a + b + carry) % 10);
carry = (a + b + carry) / 10;
dummy.next = tmp;
tmp.next = cur;
cur = tmp;
}
return dummy.next;
}
}