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

Sort List

时间:2014-05-30 15:17:18      阅读:312      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

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

bubuko.com,布布扣
/**
 * 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) 
    {
        ListNode* left;
        ListNode* right;
        quicksort(head,left,right);
        return left;
    }
    
    void quicksort(ListNode* head,ListNode*& left,ListNode*& right)
    {
        if(head==NULL)
        {
            left=NULL;right=NULL;
            return;
        }
        if(head->next==NULL)
        {
            left=head;
            right=head;
            return;
        }
        
        ListNode* headsmall=NULL;
        ListNode* smallp;
        
        ListNode* pre=head;
        ListNode* p=head->next;
        int val=head->val;
        
        bool issame=true;
        while(p!=NULL)
        {
            while(p!=NULL)
            {
                if(p->val!=val) issame=false;
                if(p->val<val) break;
                pre=p;
                p=p->next;
            }
            if(p!=NULL)
            {
                pre->next=p->next;
                if(headsmall==NULL) 
                {
                    headsmall=p;
                }
                else
                {
                    smallp->next=p;
                }
                smallp=p;
                p=p->next;
                smallp->next=NULL;
            }
        }
        //all the same
        if(issame && headsmall==NULL)
        {
            left=head;
            right=pre;
            return;
        }
        
        ListNode* headbig=head->next;
        head->next=NULL;
        
        ListNode* bigleft;
        ListNode* bigright;
        ListNode* smallleft;
        ListNode* smallright;
        
        if(headsmall!=NULL && headbig!=NULL)
        {
            quicksort(headbig,bigleft,bigright);
            quicksort(headsmall,smallleft,smallright);
            smallright->next=head;
            head->next=bigleft;
            left=smallleft;
            right=bigright;
        }
        else if(headsmall==NULL)
        {
            quicksort(headbig,bigleft,bigright);
            head->next=bigleft;
            left=head;
            right=bigright;
        }
        else if(headbig==NULL)
        {
            quicksort(headsmall,smallleft,smallright);
            smallright->next=head;
            left=smallleft;
            right=head;
        }
    }
};
bubuko.com,布布扣

 

Sort List,布布扣,bubuko.com

Sort List

标签:c   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/erictanghu/p/3759725.html

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