First, the original question
Sort List
Sort A linked list inO(NLogN) time using constant space complexity.
Second, analysis
The time complexity for quick sorting and merging sorting is O (Nlogn). If you use a merge sort, you do not need to re-apply the space to hold the sorted array in the case of a linked list, you can do the spatial complexity of the degree O (1). Here I use merge sort to sort the list.
Third, code (Java)
<pre name= "code" class= "java" >/** * Definition for singly-linked list. * Class ListNode {* int val; * ListNode Next; * ListNode (int x) {* val = x; * next = NULL; *} * } */public Class Solution {public ListNode sortlist (ListNode head) {if (head==null) return Null;head=me Rgesort (head); return head;} Public ListNode mergesort (ListNode start) {if (start.next==null) return start; ListNode P1,p2,pre;
P1=p2=pre=start;while (p1!=null) { //divides the original linked list into equal-length two-part if (p1.next!=null) {p1=p1.next.next;pre=p2;p2=p2.next;// P2 is the midpoint}else break;} Pre.next=null;start=mergesort (start);p 2=mergesort (p2); Start=merge (START,P2); return start;} Public listnode Merge (ListNode L1,listnode L2) {listnode start,temp,pre;pre=new listnode (0); if (l1.val<=l2.val Start = L1;elsestart = L2;temp=null;while ((l1!=null) && (l2!=null)) {if (l1.val<=l2.val) {pre.next=l1; temp= L1.next; L1.NEXT=L2; L1=temp; Pre=pre.next; } else{pre.next=l2; temp=l2.next; l2.next=l1; l2=temp; Pre=pre.next; }} return start;}}
"Leetcode" Sort list Solution