sorl-list

/**
 * 單鏈表的排序
 * 歸併排序的基本思想:找到鏈表的中間節點,然後遞歸對前半部分和後半部分分別進行歸併排序,最後對兩個以排好序的鏈表進行合併
 * @author cfp008
 *
 */
public class SortList
{
    class ListNode
    {
        int val;
        ListNode next;
        
        ListNode(int x)
        {
            val = x;
            next = null;
        }
    }
    
    public ListNode sort(ListNode head)
    {
        if(head == null || head.next == null)
        {
            return head;
        }
        ListNode _middle = getMiddleNode(head);//找到單鏈表的中間節點
        ListNode _next = _middle.next;
        _middle.next = null;
        
        return mergeList(sort(head), sort(_next));
    }
    
    /**
     * 利用快慢指針的思想找中間節點,快指針的速度是慢指針的兩倍
     * @param head
     * @return
     */
    public ListNode getMiddleNode(ListNode head)
    {
        ListNode _slow = head;//慢指針
        ListNode _fast = head;//快指針
        
        while(_fast.next != null && _fast.next.next != null)
        {
            _slow = _slow.next;
            _fast = _fast.next.next;
        }
        
        return _slow;
    }
   
    public ListNode mergeList(ListNode a, ListNode b)
    {
        if(a == null)
        {
            return b;
        }
        if(b == null)
        {
            return a;
        }
        ListNode _head = new ListNode(-1);
        ListNode _curr = _head;
        while(a != null && b != null)
        {
            if(a.val <= b.val)
            {
                _curr.next = a;
                a = a.next;
            }
            else
            {
                _curr.next = b;
                b = b.next;
            }
            _curr = _curr.next;
        }
        _curr.next = (a != null)? a : b;
        
        return _head.next;
    }

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