Thursday, February 5, 2015

148 Sort List

Sort a linked list in O(n log n) time using constant space complexity.
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *sortList(ListNode *head) {
        if (!head || !head->next)
            return head;
        int len=0;
        ListNode *tmp = head;
        while(tmp)
        {
            tmp=tmp->next;
            len++;
        }
        return mergeSort(head,len);
    }
    ListNode* mergeSort(ListNode *head,int n)
    {
        if (n<=1)
            return head;
        int len=n/2;
        ListNode *tmp = head;
        while(len>1)
        {
            tmp = tmp->next;
            len--;
        }
        ListNode *b = tmp->next;
        tmp->next = NULL;
        head = mergeSort(head,n/2);
        b = mergeSort(b,n-n/2);
        ListNode *newHead = merge(head,b);
        return newHead;
    }
    ListNode* merge(ListNode* a,ListNode*b)
    {
        if (!a && !b)
            return NULL;
        if (!a)
            return b;
        if (!b)
            return a;
        ListNode *dummy = new ListNode(0);
        ListNode *tmp = dummy;
        while(a && b)
        {
            if (a->val<b->val)
            {
                tmp->next = a;
                a=a->next;
            }
            else
            {
                tmp->next = b;
                b=b->next;
            }
            tmp = tmp->next;
        }
        if (a)
            tmp->next = a;
        if (b)
            tmp->next = b;
        tmp = dummy->next;
        delete dummy;
        return tmp;
    }
};

No comments:

Post a Comment