码迷,mamicode.com
首页 > 其他好文 > 详细

148. Sort List (List)

时间:2015-10-03 10:40:19      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

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

 

class Solution {
public:
    ListNode *sortList(ListNode *head) {
        if(!head || !head->next ) return head;
        return quickSort(head)[0];
    }
    
    vector< ListNode* > quickSort(ListNode *head){
        vector< ListNode* > ret;
        if(!head->next) {
            ret.push_back(head);
            ret.push_back(head);
            return ret;
        }
        ListNode* headSmaller = NULL;
        ListNode* headGreater = NULL; 
        ListNode* current = head->next;
        ListNode* prev = head;
        ListNode* tmp;
        while(current){
            if(current->val > head->val){
                prev->next = current->next;
                if(!headGreater){
                    headGreater = current;
                    headGreater->next = NULL;
                }
                else{
                    current->next  = headGreater->next;
                    headGreater->next = current;
                }
                current = prev->next;
            }
            else if(current->val < head->val){
                prev->next = current->next;
                if(!headSmaller){
                    headSmaller = current;
                    headSmaller->next = NULL;
                }
                else{
                    current->next  = headSmaller->next;
                    headSmaller->next = current;
                }
                current = prev->next;
            }
            else {
                prev = current;
                current = current->next;
            }
        }
        
        vector< ListNode* > retGreater;
        vector< ListNode* > retSmaller;
        if(headSmaller) {
            retSmaller = quickSort(headSmaller);
            retSmaller[1]->next = head;
            ret.push_back(retSmaller[0]);
        }
        else ret.push_back(head);
        if(headGreater){
           retGreater = quickSort(headGreater);
           prev->next = retGreater[0];
           ret.push_back(retGreater[1]);
        }
        else ret.push_back(prev);
        return ret;
    }
};

 

148. Sort List (List)

标签:

原文地址:http://www.cnblogs.com/qionglouyuyu/p/4853068.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!