-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreorder-list.java
72 lines (53 loc) · 1.56 KB
/
reorder-list.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
65
66
67
68
69
70
71
72
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public void reorderList(ListNode head) {
if (head == null || head.next == null)
return;
ListNode mid = midNode(head);
ListNode nhead = mid.next;
mid.next = null;
nhead = reverseList(nhead);
ListNode c1 = head;
ListNode c2 = nhead;
while (c1 != null && c2 != null) {
ListNode f1 = c1.next;
ListNode f2 = c2.next;
c1.next = c2;
c2.next = f1;
c1 = f1;
c2 = f2;
}
}
public static ListNode midNode(ListNode node) {
if (node == null || node.next == null)
return node;
ListNode slow = node, fast = node;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
public static ListNode reverseList(ListNode node) {
if (node == null || node.next == null)
return node;
ListNode prev = null;
ListNode curr = node;
while (curr != null) {
ListNode forw = curr.next; // backup.
curr.next = prev; // connection
prev = curr; // move forw.
curr = forw;
}
return prev;
}
}