Requires time complexity O (NLOGN), Spatial complexity O (1), with merge sort
The traditional merge sort space complexity is O (n), the reason is to use an array to represent the merged array, but here with the linked list to represent the chain list of ordered linked list, because the link table space complexity is O (1), so can.
Linked list problems often appear tle problem or mle problem, this time to check the link list splicing process or cycle process, see if there is a dead loop
PublicListNode sortlist (ListNode head) {if(head==NULL|| head.next==NULL)returnHead; //use the fast pointer to find the midpoint of the list and divide it into two parts recursively//to set a forward node record a slow pointer to the previous node as the end of the previous sectionListNode slow = Head,fast = Head,pre =NULL; while(fast!=NULL&&fast.next!=NULL) {Pre=slow; Slow=Slow.next; Fast=Fast.next.next; } //first half partPre.next =NULL; ListNode L1=Sortlist (head); ListNode L2=sortlist (slow); returnmerge (L1,L2); } Publiclistnode Merge (ListNode L1,listnode L2) {//set up ahead nodeListNode pre =NewListNode (0), temp =Pre; while(l1!=NULL&&l2!=NULL) { if(l1.val<l2.val) {Temp.next=L1; L1=L1.next; } Else{Temp.next=L2; L2=L2.next; } temp=Temp.next; } if(l1!=NULL) Temp.next =L1; if(l2!=NULL) Temp.next =L2; returnPre.next; }
Merge sort See: Http://www.cnblogs.com/stAr-1/p/8445377.html
[leetcode]148. Sort list Linked list merge sorting