LeetCode 148. Sort List (LinkedList的merger sort)

class Solution {
    public ListNode sortList(ListNode head) {
        if(head == null || head.next == null) return head;
        
        ListNode middle = getMiddle(head);
        ListNode l2 = middle.next;
        middle.next = null;
        
        
        return merge(sortList(head), sortList(l2));
        
    }
    
    public ListNode getMiddle(ListNode head){
        if(head == null || head.next == null) return head;
        
        ListNode slow = head;
        ListNode fast = head;
        ListNode cur = slow;
        
        while(fast != null && fast.next != null){
            cur = slow;
            slow = slow.next;
            fast = fast.next.next;
        }
        return cur;
    }
    
    public ListNode merge(ListNode l1, ListNode l2){
        ListNode dummy = new ListNode(0);
        ListNode cur = dummy;
        
        // ListNode cur1 = l1;
        // ListNode cur2 = l2;
        
        while(l1 != null && l2 != null){
            if(l1.val <= l2.val){
                cur.next = new ListNode(l1.val);
                l1 = l1.next;
            } else{
                cur.next = new ListNode(l2.val);
                l2 = l2.next;
            }
            cur = cur.next;//之前提交的时候这一句没有加 所以一直不对
        }
        if(l1 != null){
            cur.next = l1;
        } else {
            cur.next = l2;
        }
        return dummy.next;
    }
}
posted @ 2020-11-20 02:55  EvanMeetTheWorld  阅读(22)  评论(0)    收藏  举报