143. Reorder List

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}.

Solution:后半部reverse,再依次前插

思路:
1->2->3->4->5->6
(1)快慢指针找到mid,
(2)用同206题reverse a(依次reverse)或b(前部插入reverse)方法http://www.jianshu.com/p/56353df45769 将mid后的部分reverse,变为1->2->3->6->5->4
(3)以mid分界的前半部分和后半部分:将后半部 依次插入到 前半部分中,变为1->6->2->5->3->4

屏幕快照 2017-09-12 下午1.26.23.png

Time Complexity: O(N) Space Complexity: O(1)

Solution Code:

class Solution {
    public void reorderList(ListNode head) {
        if(head==null || head.next==null) return;
            
        // (1) use slow to find the middle of the list
        ListNode slow = head;
        ListNode fast = head;
        while(fast.next != null && fast.next.next != null){ 
            slow = slow.next;
            fast = fast.next.next;
        }
        ListNode mid = slow;
        
        //(2) Reverse the half after middle  1->2->3->4->5->6 to 1->2->3->6->5->4
        ListNode r_head = mid.next;
        ListNode cur = r_head;
        ListNode post = null;
        //while(cur != null & cur.next != null) {
        while(cur.next != null) {
            post = cur.next;
            cur.next = cur.next.next;
            post.next = r_head;
            r_head = post;
        }
        mid.next = r_head; // optional
            
        // (3) Reorder: Insert every the reversed list into first part
        ListNode p1 = head;
        ListNode p2 = r_head;
        while(p1 != mid){
            mid.next = p2.next;
            p2.next = p1.next;
            p1.next = p2;
            p1 = p2.next;
            p2 = mid.next;
        }
    }
}

你可能感兴趣的:(143. Reorder List)