鏈表——歸併排序

鏈表——歸併排序


在這裏插入圖片描述

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode sortList(ListNode head) {
        if (head == null || head.next == null){
            return head; 
        }
        ListNode mid = findMidNode(head);
        ListNode right = sortList(mid.next);
        mid.next = null;
        ListNode left = sortList(head);
        return merge(left, right);
    }
    
    private ListNode findMidNode(ListNode head){
        if(head == null || head.next == null)
            return head;
        ListNode slow = head;
        ListNode fast = slow.next;
        while(fast!=null && fast.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
    
    private ListNode merge(ListNode l1, ListNode l2){
        if(l1 == null || l2 == null)
            return (l1==null?l2:l1);
        ListNode head, q, p, next1, next2;
     
        if(l1.val > l2.val){
            head = l2;
            p = l2;
            q = l1;
        
        }else{
            head = l1;
            p = l1;
            q = l2;
        }
        while(p!= null && q!=null){
            
            if(p.val <= q.val){
                if(p.next == null){
                    p.next = q;
                    return head;
                }else if(p.next.val >= q.val){
                    next1 = p.next;
                    p.next = q;
                    q = next1;
                    p = p.next;
                }
                else{
                    p = p.next;
                }
            } else{
                q = q.next;
            }
            
        }
        return head;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章