Title: Sort a linked list in O(n log n) time using constant space complexity.
Analysis: to order the single-linked list, the time complexity required is O (NLOGN), the space complexity is O (1). The sorting algorithm with time complexity O (NLOGN) has a quick sort and merge sort,
However, for a single-linked list, the exchange between elements is more complicated, but it is relatively simple to connect two ordered linked lists, so the idea of merging sort is used here.
Coding:
PublicListNode sortlist (ListNode head) {if(Head = =NULL|| Head.next = =NULL) returnHead; //find the middle node of the list, a slow two pointerListNode fast =Head; ListNode Slow=Head; ListNode Pre=NULL;//record the last node of the first section//divide a single linked list into two parts while(Fast! =NULL&& Fast.next! =NULL) {Fast=Fast.next.next; Pre=slow; Slow=Slow.next; } //split the two sections open if(Pre! =NULL) Pre.next=NULL; //recursive ordering of two parts separatelyListNode L1 =Sortlist (head); ListNode L2=sortlist (slow); returnMerge (L1,L2);//Merge } //merge two ordered sequences Publiclistnode Merge (ListNode L1,listnode L2) {if(L1 = =NULL) returnL2; if(L2 = =NULL) returnL1; ListNode l=NewListNode (-1); ListNode Newhead=l; while(L1! =NULL&& L2! =NULL){ if(L1.val <l2.val) {Newhead.next=L1;//The use of a single-linked list of properties, no additional space, so that the space complexity of O (1) L1=L1.next; Newhead=Newhead.next; } Else{Newhead.next=L2; L2=L2.next; Newhead=Newhead.next; } } if(L1! =NULL) Newhead.next=L1; if(L2! =NULL) Newhead.next=L2; returnL.next; }
148. Sort list (Java for single-linked list)