Sort List

来源:互联网 发布:酒店行业数据 编辑:程序博客网 时间:2024/06/03 03:35

Description:

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


思路:

这是一道简单的单链表操作的题目。可以采用归并排序,单链表的归并排序,关键在于把原链表分为两半,可以采用快慢双指针法,快指针走两步,慢指针走一步,这样知道快指针为空时,慢指针所指的就是整个链表的中点。即可把链表一分为二。


Solution:/**
* 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;
if(head->next->next==NULL)
{
if(head->val>head->next->val)swap(head->val,head->next->val);
return head;
}
ListNode *F,*S;
F=S=head;
while(F)
{
if(F)F=F->next;
if(F)F=F->next;
else break;
if(S)S=S->next;
}
if(S==NULL)return head;
F=S->next;
S->next=NULL;
S=sortList(head);
F=sortList(F);
if(S==NULL)return F;
if(F==NULL)return S;
ListNode *res;
if(S->val<F->val)head=S,S=S->next;
else head=F,F=F->next;
res=head;
while(S && F)
{
if(S->val<F->val)head->next=S,head=S,S=S->next;
else head->next=F,head=F,F=F->next;
}
if(S==NULL)head->next=F;
if(F==NULL)head->next=S;
return res;
}
};

0 0
原创粉丝点击