Sort a linked list in O(n log n) time using constant space complexity.
Linked list, fast and slow pointer to find the midpoint, merge sort.
Pay attention to judging condition fast->next!=null&&fast->next->next!=null, if fast!=null&&fast->next!= Null will cause a memory overflow
1 /**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * ListNode *next;6 * ListNode (int x): Val (x), Next (NULL) {}7 * };8 */9 classSolution {Ten Public: OneListNode *sortlist (ListNode *head) { A if(Head==null | | head->next==NULL) - returnhead; -listnode* Slow, *fast; theslow=head; -fast=head; - while(fast->next!=null&&fast->next->next!=NULL) { -Slow=slow->Next; +Fast=fast->next->Next; - } +fast=slow; ASlow=slow->Next; atfast->next=NULL; -fast=Sortlist (head); -slow=sortlist (slow); - returnmerge (Fast,slow); - - } inListNode *merge (ListNode *left, ListNode *Right ) { -ListNode *res,*temp; to if(left==NULL) { +res=Right ; - returnRes; the } * if(right==NULL) { $res=Left ;Panax Notoginseng returnRes; - } the if(left->val<=right->val) { +res=Left ; ALeft=left->Next; the}Else{ +res=Right ; -Right=right->Next; $ } $temp=Res; - while(left!=null&&right!=NULL) { - if(left->val<=right->val) { thetemp->next=Left ; -Left=left->Next;Wuyi}Else{ thetemp->next=Right ; -Right=right->Next; Wu } -Temp=temp->Next; About $ } - if(left!=NULL) { -temp->next=Left ; - } A if(right!=NULL) { +temp->next=Right ; the } - returnRes; $ } the};
sort-list--linked list, fast and slow pointer to find the middle, merge sort