首页 > 代码库 > 148. Sort List

148. Sort List

Sort a linked list in O(n log n) time using constant space complexity.

 双链表用快排 单链表用归并

 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
 
 //归并
public class Solution {
    public ListNode sortList(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        ListNode dummy = head;
        ListNode fast = head;
        ListNode slow = head;
        while(fast != null && fast.next != null){
            dummy = slow;
            slow = slow.next;
            fast = fast.next.next;
        }
        dummy.next = null; // 断开 两条list
        ListNode l1 = sortList(head);
        ListNode l2 = sortList(slow);
        return mergeLists(l1,l2);
    }
    public ListNode mergeLists(ListNode l1, ListNode l2){
        if(l1 == null && l2 == null)
            return null;
        if(l1 == null)  
            return l2;
        if(l2 == null)
            return l1;
        if(l1.val > l2.val){
            l2.next = mergeLists(l1, l2.next);
            return l2;
        }
        else{
            l1.next = mergeLists(l1.next, l2);
            return l1;
        }
    }
}

 

148. Sort List