您的位置:首页 > 其它

leetcode No148. Sort List

2016-10-26 21:22 316 查看

Question:

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

Algorithm:

类似归并排序,程序有注释

Accepted Code:

/**
* 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) {
if(head==NULL)
return NULL;
if(head->next==NULL)
return head;

ListNode* pre=head;      //第一段的结尾
ListNode* p1=head;       //p1一次移动1个结点
ListNode* p2=head;       //p2一次移动2个结点
//目标是分成head-pre,p1-p2两段
while(p2!=NULL && p2->next!=NULL){
pre=p1;
p1=p1->next;
p2=p2->next->next;
}
pre->next=NULL;   //head-pre

ListNode* h1=sortList(head);
ListNode* h2=sortList(p1);

return Merge(h1,h2);
}
ListNode* Merge(ListNode* l1,ListNode* l2){
if(l1==NULL)
return l2;
if(l2==NULL)
return l1;
if(l1->val < l2->val){
l1->next=Merge(l1->next,l2);
return l1;
}
else{
l2->next=Merge(l1,l2->next);
return l2;
}
return NULL;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 链表