1 sorting using merge methods2 complete two main functions: Split and Merge3 The better way to split is to use the fast and slow hands, each time you find the middle part of the list to disassemble4 merging can be done in two ways: one is a non-recursive method and the other is a recursive method, all of which can be used.5 individuals prefer recursive methods, which are easier to understand .6 /**7 * Definition for singly-linked list.8 * struct ListNode {9 * int val;Ten * ListNode *next; One * ListNode (int x): Val (x), Next (NULL) {} A * }; - */ - classSolution { the Public: -listnode* mergelist (ListNode * list1, listnode*list2) - { - if(List1 = =NULL) + returnList2; - if(List2 = =NULL) + returnList1; AListNode * Phead =NULL; at if(List1->val < list2->val) - { -Phead =List1; -Phead->next = Mergelist (list1->next,list2); - } - Else in { -Phead =List2; toPhead->next = Mergelist (list2->Next, List1); + } - returnPhead; the } * $ListNode *sortlist (ListNode *head) {Panax Notoginseng if(head = = NULL | | head->next = = NULL)returnhead; -listnode* slow =head; thelistnode* fast = head->Next; + while(Fast && fast->next) A { theFast = Fast->next->Next; +slow = slow->Next; - } $ListNode * headb = slow->Next; $Slow->next =NULL; - returnMergelist (Sortlist (head), Sortlist (HEADB)); - } the};
Sort a linked list in O (n log n) time using constant space complexity.