reorder-list

Given a singly linked list L: L 0L 1→…→L n-1L n,

reorder it to: L 0L n L 1L n-1L 2L n-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}.


public class ReorderList
{
    //節點數據結構
    static class ListNode
    {
        int val;
        ListNode next;
        
        ListNode(int x)
        {
            val = x;
            next = null;
        }
    }
    
    public static void reorderList(ListNode head)
    {
        if(null == head || null == head.next)
        {
            return;
        }
        //快慢指針找到中間節點
        ListNode _slow = head;
        ListNode _fast = head;
        while( null != _fast.next  &&  null != _fast.next.next)
        {
            _slow = _slow.next;
            _fast = _fast.next.next;
        }
        //拆分鏈表,並反轉中間節點之後的鏈表
        //後一個鏈表的節點數與前一個鏈表相同或少一個
        ListNode _after = _slow.next;
        _slow.next = null;
        ListNode _node = null;
        //反轉時,依次遍歷每個節點,依次將每個節點的next指向原來的前一個節點
        while(null != _after)
        {
            ListNode _next = _after.next;
            _after.next = _node;
            _node = _after;
            _after = _next;
        }
        //合併鏈表
        _after = _node;//後一個鏈表的第一個節點
        ListNode _first = head;
        while(null != _after)
        {
            ListNode _tempFirst = _first.next;
            ListNode _tempAfter = _after.next;
            _after.next = _first.next;
            _first.next = _after;
            _first = _tempFirst;
            _after = _tempAfter;
        }
        
    }
   
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章