Sort List 归并排序链表
原创
©著作权归作者所有:来自51CTO博客作者我想有个名字的原创作品,请联系作者获取转载授权,否则将追究法律责任
Sort List
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) {
if(head==NULL || head->next==NULL)
return head;
ListNode *mid=getMid(head);
ListNode *next=mid->next;
mid->next=NULL;
return merge(sortList(head),sortList(next));
}
ListNode *getMid(ListNode *head)
{
ListNode *slow=head;
ListNode *fast=head;
while(fast->next!=NULL&&fast->next->next!=NULL)
{
slow=slow->next;
fast=fast->next->next;
}
return slow;
}
ListNode *merge(ListNode *a,ListNode *b)
{
ListNode *help=new ListNode(0);
ListNode *cur=help;
while(a!=NULL && b!=NULL)
{
if(a->val<b->val)
{
cur->next=a;
a=a->next;
}else
{
cur->next=b;
b=b->next;
}
cur=cur->next;
}
cur->next=(a!=NULL)?a:b;
return help->next;
}
};