Description:
Sort a linked list in O(n log n) time using constant space complexity.
对链表排序,时间复杂度的要求是O(n log n),空间复杂度的要求比较模糊但尽量占用更少的空间就没错
算法思路:
看见这个时间复杂度的要求我们就会想到高级排序,故可以使用分治策略。
先将链表一分为二,再递归调用sort函数不断地分割链表直至分成了一个一个的结点,最后返回排序的结果,
思路与快排、归并的思路一致
class Solution {
public:
ListNode* Merge(ListNode* head1,ListNode* head2)
{
ListNode *ps=new ListNode(0); //注意了
ListNode *p1=ps; //要将排序后的链表存储在p1指向的地址
while(head1||head2)
{
if(head1&&(!head2||head1->val<=head2->val))
{
p1=p1->next=head1;
head1=head1->next;
}
else if(head2&&(!head1||head2->val<head1->val)) //不要用<=
{
p1=p1->next=head2;
head2=head2->next;
}
}
p1->next=NULL;
return ps->next;
}
ListNode* sortList(ListNode* head) {
//利用快慢指针法找出中间结点,而后进行分割
if(!head||!head->next)
return head;
ListNode *fast,*slow;
fast=head->next;
slow=head;
while(fast&&fast->next)
{
fast=fast->next->next;
slow=slow->next;
}
ListNode *p=slow->next;
slow->next=NULL;
return Merge(sortList(head),sortList(p));
}
};
注意:
在该题中,快指针fast初始指向head->next
当fast=head 时间就会超出,而等于head->next时 却不会
例如,只有两个结点2—>1的时候,假如fast=head;由于fast存在,fast->next也存在,故执行while语句,
此时slow也移动,使得分割出现错误,算法失败
当然,上述算法有不足之处,那就是:可能会发生memory leak
今天想到了解决memory leak的方法:
ListNode *t=ps->next;
delete ps;
return t;
另一种写法:
public class Solution {
//merge two sorted list, return result head
public ListNode merge(ListNode h1, ListNode h2){
if(h1 == null){
return h2;
}
if(h2 == null){
return h1;
}
if(h1.val < h2.val){
h1.next = merge(h1.next, h2);
return h1;
}
else{
h2.next = merge(h1, h2.next);
return h2;
}
}
public ListNode sortList(ListNode head) {
//bottom case
if(head == null){
return head;
}
if(head.next == null){
return head;
}
//p1 move 1 step every time, p2 move 2 step every time, pre record node before p1
ListNode p1 = head;
ListNode p2 = head;
ListNode pre = head;
while(p2 != null && p2.next != null){
pre = p1;
p1 = p1.next;
p2 = p2.next.next;
}
//change pre next to null, make two sub list(head to pre, p1 to p2)
pre.next = null;
//handle those two sub list
ListNode h1 = sortList(head);
ListNode h2 = sortList(p1);
return merge(h1, h2);
}
}