Sort a linked list in O(n log n) time using constant space complexity.
这个题有不少细节需要注意。完全实现不是很容易。
注意点:1,如何像数组一样,把链表分组? 答:可以用快慢两个指针来搞定,但是注意链表一定要断开。
2,如何防止无限的归并下去。就是有一组一直是NULL;注意检验,快慢指针停止的条件。
代码如下:
class Solution {
public:
ListNode* sortList(ListNode* head) {
if(head==NULL||head->next==NULL) return head;
ListNode *slow(head),*fast(head);
for(;fast->next!=NULL&&fast->next->next!=NULL;fast=fast->next->next,slow=slow->next);//注意循环判断的条件!!!
//断开原来的链表
fast=slow;
slow=slow->next;
fast->next=NULL;
ListNode *p1=sortList(head);
ListNode *p2=sortList(slow);
return mergeTwoLists(p1,p2);
}
private:
ListNode* mergeTwoLists(ListNode* head,ListNode* slow)
{
if(head==NULL) return slow;
if(slow==NULL) return head;
ListNode dummy(-1);
ListNode* p=&dummy;
for(;head!=NULL&&slow!=NULL;p=p->next)
{
if(head->val<=slow->val)
{
p->next=head;
head=head->next;
}else{
p->next=slow;
slow=slow->next;
}
}
p->next=head!=NULL?head:slow;
return dummy.next;
}
};此题不小心便会陷入无限循环的陷阱。
本文介绍了一种使用常数空间复杂度,在O(n log n)时间内对链表进行排序的方法。文章详细阐述了通过快慢指针技巧将链表分组,并避免无限递归的问题。此外,还提供了完整的C++实现代码。
1258

被折叠的 条评论
为什么被折叠?



