lintcode:Sort List

来源:互联网 发布:网络主播盈利模式 编辑:程序博客网 时间:2024/05/15 01:55

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

Example

Given 1-3->2->null, sort it to 1->2->3->null.

/** * Definition of ListNode * class ListNode { * public: *     int val; *     ListNode *next; *     ListNode(int val) { *         this->val = val; *         this->next = NULL; *     } * } */class Solution {public:    /**     * @param head: The first node of linked list.     * @return: You should return the head of the sorted linked list,                    using constant space complexity.     */         ListNode *getMidNode(ListNode *head)    {        if (!head)            return NULL;                    ListNode *pSlowNode = head;        ListNode *pFastNode = head;                while (pFastNode->next && pFastNode->next->next)        {            pFastNode = pFastNode->next->next;            pSlowNode = pSlowNode->next;        }                return pSlowNode;    }         ListNode *mergeNode(ListNode *head1, ListNode *head2)    {        if (!head1 && !head2)            return NULL;        else if (head1 == NULL)            return head2;        else if (head2 == NULL)            return head1;                ListNode fakeHead(-1);                ListNode *pCurNode = &fakeHead;        ListNode *p1 = head1;        ListNode *p2 = head2;                while (p1 && p2)        {            if (p1->val <= p2->val)            {                pCurNode->next = p1;                p1 = p1->next;            }            else            {                pCurNode->next = p2;                p2 = p2->next;            }            pCurNode = pCurNode->next;        }                if (p1)            pCurNode->next = p1;        if (p2)            pCurNode->next = p2;                    return fakeHead.next;    }         ListNode *sortList(ListNode *head) {        // write your code here        if (!head)            return NULL;                    if (head->next == NULL)            return head;                    ListNode *midNode = getMidNode(head);        ListNode *p1 = head;        ListNode *p2 = midNode->next;                midNode->next = NULL;                ListNode *n1 = sortList(p1);        ListNode *n2 = sortList(p2);                return mergeNode(n1, n2);    }};


0 0