Sort a linked list in O(n log n) time using constant space complexity.
Time complexity is O (NLOGN), you can think of merge sort, quick row, bucket sort.
Idea: Using merge sort, the whole can be divided into two bodies, one, the construction of two sorted sub-linked list; second, the sub-linked list is merged. For the first part, you can use the method of fast and slow pointer, split the linked list, and then recursively sort the nodes; for the second part, take out the table header nodes of the two sub-linked lists to compare size, small first put into the new linked list. For the later great God's removal of newlist skills, you can seriously study. The code is as follows
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; the returnMergetwo (head); - } - -ListNode *mergetwo (ListNode *head) + { - if(head==null| | head->next==NULL) + returnhead; AListNode *preslow=NULL; atListNode *slow=head,*fast=head; - - while(fast&&fast->next) - { -preslow=slow; -Slow=slow->Next; inFast=fast->next->Next; - } topreslow->next=NULL; +ListNode *left=Mergetwo (head); -ListNode *right=mergetwo (slow); the returnmegertwolists (left,right); * } $ Panax NotoginsengListNode *megertwolists (ListNode *left,listnode *Right ) - { theListNode *newlist=NewListNode (-1); + AListNode *pre=NewList; the while(left&&Right ) + { - if(Left->val > right->val) $ { $pre->next=Right ; -Right=right->Next; - } the Else - {Wuyipre->next=Left ; theLeft=left->Next; - } WuPre=pre->Next; - } About if(left) $pre->next=Left ; - Else -pre->next=Right ; - A //Here's how the Great Gods are written. Can also be written directly as return newlist->next; but will cause a memory leak? +Slow=newlist->Next; thenewlist->next=NULL; - DeleteNewList; $ the returnslow; the } the};
[Leetcode] Sort list sorting linked list