leetcode-sort list

来源:互联网 发布:windows服务 编辑:程序博客网 时间:2024/05/22 13:21

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

思路:

归并排序:找到链表的中间结点,对两个已有序链表进行合并。

代码:

ListNode* mergeList(ListNode *p, ListNode *q)
{
ListNode head(0);
ListNode *cur=&head;
while(p!=NULL && q!=NULL)
{
if(p->val<=q->val)
{
cur->next=p;
p=p->next;
}
else
{
cur->next=q;
q=q->next;
}
cur=cur->next;
}
cur->next=p!=NULL?p:q;
return head.next;


}
ListNode *sortList(ListNode *head) 
{
if(head==NULL || head->next==NULL)
return head;


ListNode *p=head;
ListNode *q=head;
while(p->next!=NULL && q->next->next!=NULL)
{
p=p->next;
q=q->next;
}
ListNode *midNext=p->next;
p->next=NULL;
return mergeList(sortList(head),sortList(midNext));
}

0 0