leetcode143~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}

思路: 1 利用倆指針找到中間節點,將鏈表分爲兩個部分
2 對後半部分的鏈表進行逆序
3 合併兩個鏈表

public void reorderList(ListNode head) {
        if(head==null || head.next==null) return;
        ListNode fast = head;
        ListNode slow = head;
        while(fast.next!=null && fast.next.next!=null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        //此時slow是中間的節點
        ListNode rhead = slow.next;
        slow.next = null;
        rhead = reverse(rhead);

        //合併鏈表
        while(head!=null && rhead!=null) {
            ListNode tmp1 = head.next;
            ListNode tmp2 = rhead.next;
            head.next = rhead;
            rhead.next = tmp1;

            head = tmp1;
            rhead = tmp2;
        }
    }

    //翻轉
    private ListNode reverse(ListNode head) {
        ListNode pre = null;
        while(head!=null) {
            ListNode tmp = head.next;
            head.next = pre;
            pre = head;
            head = tmp;
        }
        return pre;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章