Sort a linked list in O(n log n) time using constant space complexity.
根据题目O(nlogn)时间,O(1)空间,选择了归并排序
/**
* 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) return NULL;
if(!head->next) return head;
// ListNode*pre=new ListNode(-1);
/* pre->next=head;
ListNode *fast=pre->next,*slow=pre->next->next;
while(slow->next&&slow->next->next){
fast=fast->next;
slow=slow->next->next;
}
fast->next=NULL;*/
ListNode *slow = head, *fast = head, *pre = head;
while (fast && fast->next) {
pre = slow;
slow = slow->next;
fast = fast->next->next;
}
pre->next = NULL;
// sortList(fast);sortList(slow);
// return merge(fast,slow);
// sortList(head);sortList(slow);
// return merge(head,slow);
return merge(sortList(head), sortList(slow));
}
ListNode* merge(ListNode* first,ListNode *second){
ListNode *temp=new ListNode(-1),*p=first,*q=second,*pre;
pre=temp;
while(p&&q){
if(p->val>q->val) {temp->next=q;q=q->next;}
else{temp->next=p;p=p->next;}
temp=temp->next;
}
if(p) temp->next=p;//这里由while改成了if
if(q) temp->next=q;
return pre->next;
}
};
打了注释的地方都是错误点