Sort List

来源:互联网 发布:淘宝网服装男士 编辑:程序博客网 时间:2024/06/16 11:19

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 )    {        vector<int> vec;        ListNode *p = head;        while( p != NULL )        {            vec.push_back( p->val );            p = p->next;        }                vector<int> tmp( vec.size() );                mergeSort( vec, tmp, 0, vec.size() - 1 );                p = head;        for(vector<int>::iterator it = vec.begin(); it != vec.end(); it++, p = p->next)            p->val = *it;                    return head;    }        void mergeSort( vector<int> &vec, vector<int> &tmp, int left, int right )    {        if( left < right )        {            int center = ( left + right ) / 2;            mergeSort( vec, tmp, left, center );            mergeSort( vec, tmp, center + 1, right );            merge( vec, tmp, left, center + 1, right );        }    }        void merge( vector<int> &vec, vector<int> &tmp, int leftPos, int rightPos, int rightEnd )    {        int leftEnd = rightPos - 1;        int tmpPos = leftPos;        int numElements = rightEnd - leftPos + 1;                while(leftPos <= leftEnd && rightPos <= rightEnd)            if(vec[leftPos] < vec[rightPos])                tmp[tmpPos++] = vec[leftPos++];            else                tmp[tmpPos++] = vec[rightPos++];                        while(leftPos <= leftEnd)            tmp[tmpPos++] = vec[leftPos++];                    while(rightPos <= rightEnd)            tmp[tmpPos++] = vec[rightPos++];                    for(int i = 0; i < numElements; i++, rightEnd--)            vec[rightEnd] = tmp[rightEnd];    }};


0 0