首页 > 其他 > 详细

sort-list

时间:2017-08-01 17:32:48      阅读:261      评论:0      收藏:0      [点我收藏+]
/*sort-list*/
/**************/
/*
Sort a linked list in O(n log n) time using constant space complexity.
*/
/*************/

struct ListNode{
    int val;
    ListNode *next;
    ListNode(int x):val(x){}
}

ListNode *sortList(ListNode *head)
{
    if(head==NULL || head->next==NULL) return head;
    ListNode *slow=head,*fast=head->next;
    while(fast && fast->next){
         slow=slow->next;
         fast=fast->next->next;
    }
    ListNode *l1=sortList(slow->next);
    slow->next=NULL;
    ListNode *l2= sortList(head);
    return merge(l1,l2);  
}

ListNode *merge(ListNode *l1,ListNode *l2)
{
    ListNode head(0);
    ListNode *p=&head;
    while(l1&&l2){
         if(l1->val<=l2->val){
             p->next=l1;
             l1=l1->next;
         }else{
             p->next=l2;
             l2=l2->next;
         }
         p=p->next;
     }
     if(l1) p->next=l1;
     if(l2) p->next=l2;
     return head.next;
}

 

sort-list

原文:http://www.cnblogs.com/wangdake-qq/p/7269639.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!