LeetCode 9 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' value.
For example,
Given {1,2,3,4}, reorder it to {1,4,2,3}.
分析:
1、速遅針法でチェーンテーブルの真ん中に突き刺し、チェーンテーブルを切断し、
2、チェーンテーブルの後半を反転し、
3、さらに2つの部分を1つのチェーンテーブルに合成します.
注意:チェーンテーブルのテーマに偽のノードを導入すると、多くの便利さをもたらします.
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public void reorderList(ListNode head) {
        if(head==null || head.next==null) return;
        ListNode slow = head;
        ListNode fast = head;
        while(fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
        }
        ListNode l1 = head;
        ListNode l2 = slow.next;
        slow.next = null;
        l2 = reverseList(l2);
        head = mergeList(l1, l2);
    }
    
    private ListNode reverseList(ListNode head){
        if(head == null || head.next == null) return head;
        ListNode newHead = new ListNode(0);
        newHead.next = head;
        ListNode last = newHead.next;
        ListNode cur = last.next;
        while(cur != null){
            last.next = cur.next;
            cur.next = newHead.next;
            newHead.next = cur;
            cur = last.next;
        }
        return newHead.next;
    }
    
    private ListNode mergeList(ListNode l1, ListNode l2){
        ListNode p1 = l1;
        ListNode p2 = l2;
        ListNode newHead = new ListNode(0);
        ListNode p = newHead;
        while(p1 != null && p2 !=null){
            p.next = p1;
            p = p.next;
            p1 = p1.next;
            p.next = p2;
            p = p.next;
            p2 = p2.next;
        }
        if(p1 == null){
            p.next = p2;
        }
        if(p2 == null)
            p.next = p1;
        return newHead.next;
    }
}