143. Reorder List - jiejackyzhang/leetcode-note GitHub Wiki
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}.
解题思路为:
- 找到list的中点,将list断开;
 - reverse后半部分;
 - merge两部分。
 
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void reorderList(ListNode head) {
        if(head == null || head.next == null) return;
        // find mid point
        ListNode mid = head;
        ListNode tail = head;
        while(tail != null && tail.next != null) {
            mid = mid.next;
            tail = tail.next.next;
        }
        // split
        ListNode cur = mid.next;
        mid.next = null;
        // reverse list2
        ListNode prev = null;
        while(cur != null) {
            ListNode temp = cur.next;
            cur.next = prev;
            prev = cur;
            cur = temp;
        }
        // merge
        ListNode l1 = head;
        ListNode l2 = prev;
        while(l2 != null) { // list2 has fewer nodes
            ListNode temp = l2.next;
            l2.next = l1.next;
            l1.next = l2;
            l1 = l2.next;
            l2 = temp;
        }
    }
}