Thursday, January 16, 2014

LeetCode : Sort a linked list

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

    public ListNode merge(ListNode sA,ListNode sB)
    {
        if(sA==null)return sB;
        if(sB==null)return sA;
        ListNode hA=sA;
        ListNode hB=sB;
        ListNode x=null;
        ListNode hR=null;
        ListNode lR=null;
        while(!(hA==null&&hB==null))
        {
            if(hB==null)
            {
                x=hA;
                hA=hA.next;
            }
            else if(hA==null)
            {
                x=hB;
                hB=hB.next;
            }
            else if(hA.val<hB.val)  // Beware hA or hB is null
            {
                x=hA;
                hA=hA.next;
            }
            else
            {
                x=hB;
                hB=hB.next;
            }
         
            x.next=null;
            if(lR==null)
                hR=x;
            else
                lR.next=x;
            lR=x;
        }
        return hR;
    }
 
    public ListNode sortList(ListNode head) {
        if(head==null)return null;
        if(head.next==null)return head;
        ListNode q1=head,p1=head,p2=head;

// Seperate the link list in O(n);
        while(true)
        {
            if(p2.next==null)break;
            p2=p2.next;
            q1=p1;
            p1=p1.next;
            if(p2.next==null)break;
            p2=p2.next;
        }
        q1.next=null;
        if(p1==head)p1=null;

        return merge(sortList(head),sortList(p1));
    }

No comments:

Post a Comment