LC.143.Reorder List
https://leetcode.com/problems/reorder-list/description/
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes' values.
For example,
Given {1,2,3,4}, reorder it to {1,4,2,3}.
time: o(n) space: o(1)
1 public void reorderList(ListNode head) {
2 if (head == null || head.next == null) return;
3 ListNode mid = null;
4 ListNode l1 = head;
5 // step 1: find the mid
6 mid = findMid(head);
7 ListNode l2 = mid.next ;
8 //重要!断开中点和后一段
9 mid.next = null;
10 //step 2: reverse the 2nd half
11 ListNode l2Reverse = reverse(l2);
12 //step 3: merge with the 1st with the 2nd
13 merge(l1, l2Reverse);
14 }
15
16 //去中点
17 private ListNode findMid(ListNode head){
18 ListNode fast = head, slow = head;
19 while (fast != null && fast.next != null && fast.next.next != null) {
20 fast = fast.next.next;
21 slow = slow.next;
22 }
23 return slow ;
24 }
25
26 //reverse
27 private ListNode reverse(ListNode head) {
28 if (head == null || head.next == null) return head;
29 ListNode pre = null;
30 ListNode curr = head;
31 while (curr != null) {
32 ListNode temp = curr.next;
33 curr.next = pre;
34 pre = curr;
35 curr = temp;
36 }
37 return pre;
38 }
39
40 //合并
41 private ListNode merge(ListNode head1, ListNode head2) {
42 ListNode curr1 = head1, curr2 = head2, temp1 = null, temp2 = null;
43 while (curr1.next != null && curr2 != null) {
44 temp1 = curr1.next;
45 temp2 = curr2.next;
46 curr1.next = curr2;
47 curr2.next = temp1;
48 curr1 = temp1;
49 curr2 = temp2;
50 }
51 if (curr2 != null) {
52 curr1.next = curr2;
53 curr2.next = null;
54 }
55 else {
56 curr1.next = null;
57 }
58 return head1;
59 }