-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathReorderList.java
More file actions
67 lines (59 loc) · 1.16 KB
/
ReorderList.java
File metadata and controls
67 lines (59 loc) · 1.16 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
/**
*
*/
package cc.dectinc.leetcode;
import cc.dectinc.api.structs.ListNode;
/**
* @author Dectinc
* @version Apr 15, 2015 4:52:43 PM
*
*/
public class ReorderList {
public void reorderList(ListNode head) {
if (head == null || head.next == null) {
return;
}
// get last half using fast and slow
ListNode p = head, q = head.next;
while (q != null && q.next != null) {
p = p.next;
q = q.next.next;
}
q = p.next;
p.next = null;
p = head;
q = reverseList(q);
ListNode t;
while (p != null) {
t = p.next;
p.next = q;
p = t;
if (q != null) {
t = q.next;
q.next = p;
q = t;
}
}
}
public ListNode reverseList(ListNode head) {
ListNode root = new ListNode(0);
root.next = head;
ListNode p, q, t;
p = t = root.next;
q = p.next;
while (q != null) {
t.next = q.next;
root.next = q;
q.next = p;
p = q;
q = t.next;
}
return root.next;
}
public static void main(String[] args) {
ReorderList sol = new ReorderList();
ListNode head = ListNode.constructList(new Integer[] { 1, 2, 3, 4, 5 });
sol.reorderList(head);
System.out.println(ListNode.convertLinkedListToList(head));
}
}