148. Sort List

Sort a linked list inO(nlogn) time using constant space complexity.

思路:插入排序

public class Solution {
    public ListNode sortList(ListNode head) {
        if (head==null||head.next==null){
            return head;
        }    

        ListNode prev = null;
        ListNode slow = head;
        ListNode fast = head;

        while (fast!=null&&fast.next!=null){
            prev = slow;
            slow = slow.next;
            fast = fast.next.next;
        }
        prev.next = null;

        ListNode l1 = sortList(head);
        ListNode l2 = sortList(slow);

        return merge(l1,l2);
    }



    public ListNode merge(ListNode l1, ListNode l2){
        ListNode l = new ListNode(0);
        ListNode p = l;
        while(l1!=null&&l2!=null){
            if (l1.val<l2.val){
                p.next = l1;
                l1 = l1.next;
            }else{
                p.next = l2;
                l2 = l2.next;
            }
            p = p.next;
        }

        if (l1!=null){
            p.next = l1;
        }

        if (l2!=null){
            p.next = l2;
        }

        return l.next;
    }
}

C#: // Line 15: An implicitly typed local variable declaration cannot be initialized with `null';

public class Solution {
    public ListNode SortList(ListNode head) 
    {
        if(head == null || head.next == null)
            return head;
        //var prev = null;
        var slow = head;
        var fast = head;
        while(fast.next != null && fast.next.next != null)
        {
            slow = slow.next;
            fast = fast.next.next;
        }
        //以下段落与java有区别
        var h1 = head;
        var h2 = slow.next;
        slow.next = null;
        h1 = SortList(h1);
        h2 = SortList(h2);
        //以上段落与java有区别
        return Merge(h1, h2);
    }



    private ListNode Merge(ListNode h1, ListNode h2)
    {
        var dummy = new ListNode(0);
        var pre = dummy;
        while(h1 != null && h2 != null)
        {
            if(h1.val < h2.val)
            {
                pre.next = h1;
                h1 = h1.next;
            }
            else
            {
                pre.next = h2;
                h2 = h2.next;
            }
            pre = pre.next;
        }
        if(h1 != null)
        {
            pre.next = h1;
        }
        else
        {
            pre.next = h2;
        }
        return dummy.next;
    }
}

results matching ""

    No results matching ""