The problem:
Sort a linked list in O(n log n) time using constant space complexity.
My Analysis:
The is problem could was elegantly solved by using the merge.
The inefficient-on IS-to-scan the lists from the first list to the end list. However this-is-too inefficient, each element of the list needed to be compared i-1 times. (Lists[i])
An elegant-on-a-is-use-from-merge sort. We could merge the lists in binary.
To achieve this goal, we need to define the recursion. (It includes some skills)
1. We use the Indexes:low and high, the partition into the parts, then the sort and each partition respectively.
A. IFF low < High, we partition the lists into <low .... mid>, <mid + 1 ..... high>.
B. iff low = = high, there is only one list (Lists[low]) left in the lists, we could directly return it. (Base case)
2. Merge the partitions, and return the result as one linked list.
My Solution:
Public classSolution { PublicListNode sortlist (ListNode head) {returnMergeSort (head); } PrivateListNode mergesort (ListNode head) {if(Head = =NULL|| Head.next = =NULL)//The base case in the recursion is very important! returnHead; ListNode Walker=Head; ListNode Runner=Head; while(Runner.next! =NULL&& Runner.next.next! =NULL) {//Skill:check Runner.next at first.Walker= Walker.next;//This skill is amazing!!!Runner =Runner.next.next; } ListNode head2=Walker.next; Walker.next=NULL; ListNode Head1=Head; Head1=mergesort (HEAD1); Head2=mergesort (head2); Head=merge (Head1, head2); returnHead; } Privatelistnode Merge (ListNode head1, ListNode head2) {if(Head1 = =NULL&& Head2 = =NULL) return NULL; if(Head1 = =NULL&& head2! =NULL) returnhead2; if(Head1! =NULL&& Head2 = =NULL) returnHead1; ListNode Dummy=NewListNode (0); ListNode Pre=dummy; ListNode ptr1=Head1; ListNode PTR2=head2; while(Ptr1! =NULL&& PTR2! =NULL) { if(Ptr1.val <=ptr2.val) {Pre.next=ptr1; Pre=Pre.next; PTR1=Ptr1.next; } Else{Pre.next=ptr2; Pre=Pre.next; PTR2=Ptr2.next; } } if(PTR1 = =NULL) Pre.next=ptr2; ElsePre.next=ptr1; returnDummy.next; }}
[Leetcode#23] Merge k Sorted Lists