Sort a linked list in O(n log n) time using constant space complexity.
Common sorting methods are many, insert sort, choose Sort, heap sort, quick sort, bubble sort, merge sort, bucket sort, etc... Their time complexity is not the same, and here the topic limit time must be O (NLGN), meet the requirements of only fast sorting, merge sort, heap sorting, and according to the characteristics of single-linked list, the most suitable for merging sort. The code is as follows:
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode*sortlist (ListNode *head) { if(!head | |!head->next)returnHead; ListNode*fast = head, *slow =Head; while(Fast->next && fast->next->next) {Slow= slow->Next; Fast= fast->next->Next; } Fast=slow; Slow= slow->Next; Fast->next =NULL; Fast=Sortlist (head); Slow=sortlist (slow); returnmerge (fast, slow); } ListNode*merge (ListNode *head1, ListNode *head2) {ListNode*res =NewListNode (-1); ListNode*cur =Res; while(Head1 &&head2) { if(Head1->val < head2->val) {cur->next =Head1; Head1= head1->Next; } Else{cur->next =head2; Head2= head2->Next; } cur= cur->Next; } if(head1) Cur->next =Head1; if(head2) Cur->next =head2; returnRes->Next; }};
[Leetcode] Sort list Linked list sorting