forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
64 lines (55 loc) · 1.51 KB
/
Solution.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
57
58
59
60
61
62
63
64
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public void reorderList(ListNode head) {
if (head == null || head.next == null || head.next.next == null) {
return;
}
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode slow = head;
ListNode fast = head;
ListNode pre = dummy;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
pre = pre.next;
}
pre.next = null;
// 将后半段的链表进行 reverse
ListNode rightPre = new ListNode(-1);
rightPre.next = null;
ListNode t = null;
while (slow != null) {
t = slow.next;
slow.next = rightPre.next;
rightPre.next = slow;
slow = t;
}
ListNode p1 = dummy.next;
ListNode p2 = p1.next;
ListNode p3 = rightPre.next;
ListNode p4 = p3.next;
while (p1 != null) {
p3.next = p1.next;
p1.next = p3;
if (p2 == null) {
break;
}
p1 = p2;
p2 = p1.next;
p3 = p4;
p4 = p3.next;
}
if (p4 != null) {
p1.next.next = p4;
}
head = dummy.next;
}
}