-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReorderListII.java
More file actions
43 lines (36 loc) · 980 Bytes
/
ReorderListII.java
File metadata and controls
43 lines (36 loc) · 980 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
41
42
43
import java.util.LinkedList;
import java.util.Stack;
/**
* 026/143 重排链表
*/
public class ReorderListII {
public void reorderList(ListNode head) {
ListNode middle = findMiddle(head);
Stack<ListNode> stack = new Stack<>();
while (middle != null) {
stack.push(middle);
middle = middle.next;
}
ListNode left = head;
ListNode right;
while (!stack.isEmpty()) {
ListNode temp = left.next;
right = stack.pop();
left.next = right;
right.next = temp;
left = temp;
}
}
ListNode findMiddle(ListNode head) {
ListNode slow=new ListNode(-1, head);
ListNode fast=slow;
while(fast!=null && fast.next!=null) {
slow = slow.next;
fast = fast.next.next;
}
// 阶段中点
ListNode res = slow.next;
slow.next = null;
return res;
}
}