Sort a linked list in O(n log n) time using constant space complexity.
1 class Solution { 2 public: 3 ListNode *sortList(ListNode *head) 4 { 5 if(!head||!head->next) return head; 6 return mergeSort(head); 7 } 8 ListNode* mergeSort(ListNode* head) { 9 if(head==NULL||head->next==NULL) return head; 10 11 ListNode *p=head; 12 ListNode *q=head; 13 ListNode *pre=NULL; 14 15 while(q&&q->next!=NULL) 16 { 17 q=q->next->next; 18 pre=p; 19 p=p->next; 20 } 21 22 pre->next=NULL; 23 24 ListNode *left=mergeSort(head); 25 ListNode *right=mergeSort(p); 26 27 return merge(left,right); 28 } 29 30 ListNode *merge(ListNode *left,ListNode *right) 31 { 32 ListNode *tmp=new ListNode(0); 33 ListNode *p=tmp; 34 while(left&&right) 35 { 36 if(left->val<=right->val) 37 { 38 p->next=left; 39 left=left->next; 40 }else 41 { 42 p->next=right; 43 right=right->next; 44 } 45 46 p=p->next; 47 } 48 49 if(!left) 50 p->next=right; 51 else 52 p->next=left; 53 54 p=tmp->next; 55 tmp->next=NULL; 56 delete tmp; 57 return p; 58 } 59 60 };