Leetcode on the topic:
Sort A linked list inO(NLogN) time using constant space complexity.
The initial idea was to hurry up because of the requirement for space overhead O (1), but some cases could not be passed, and everyone understood that the worst time spent in the queue O (n^2)
So you still have to use the merge sort, the O (n) space overhead is generally required for the array merge sort, but there is also the in-place merge sort to do the O (1) space overhead, which is too complex
Always remember.
But for the linked list, it is relatively simple to do O (1) space overhead, just pay attention to some boundary conditions.
Public ListNode sortlist (ListNode head) {if (head==null| | Head.next==null) return head; ListNode Tail=head;int len=1; while (tail.next!=null) {tail=tail.next; len++; } head=mergesort (Null,head,len); return head;} Return the head of sorted list.private ListNode mergesort (listnode prehead,listnode head, int len) {if (head==null| | len<=1) return Head;int left=len/2;int Right=len-left;//sort left Parthead=mergesort (prehead,head,left);//sort Right Partlistnode pmid=head;for (int i=0;i<left-1;i++) {pmid=pmid.next;} MergeSort (pmid,pmid.next,right);//p1 points to left part head,p2 points to right part headlistnode P1=head,p2=pmid.next; ListNode pre1=prehead,pre2=pmid;//new Head is little one between left head and right head. if (p1.val>p2.val) head=p2;while (left>0&&right>0) {//if p2.val<p1.val move P2 previous to P1.if ( P1.val>p2.val) {//delete p2pre2.next=p2.next;//add p2 previous to p1p2.next=p1;if (pre1!=null) {pre1.next=p2;} Pre1 move to P2PRE1=P2;//P2 move to pre2.nextp2=pre2.next;right--;} else{pre1=p1;p1=p1.next;left--;}} return head;}
Sort list, Time overhead O (NLOGN), Space overhead O (1)