Sort a linked list in O (n log n) time using the constant space complexity.
Everybody read the topic and guess like me ... Are thinking what is nlogn Ah ~ Quick Sort, merge sort, heap sort. Then began to worry, these things become a list of how to do ah ...
But I remember deeply in the CMU when the teacher told me that Java now with the Arrays.sort with the Fast Platoon, and then I think, then ... Why not turn the list into an array and put it back in line?
So I used a ArrayList first installed this list, and then the ArrayList into an array to sort, and then put the results into a linkedlist return to the head knot ~ write here they all want to be happy, and stupid and fun method ~
Not to say, directly on the code ~ has passed the Leetcode test ~ with test main function
import java.util.ArrayList; import java.util.Arrays;
public class Sortlist {public static void main (String args[]) {sortlist DP = new Sortlist ();
ListNode head = new ListNode (3);
ListNode p1 = new ListNode (2);
HEAD.NEXT=P1;
ListNode P2 = new ListNode (1);
P1.next = p2;
ListNode p3 = new ListNode (5);
P2.next = p3;
ListNode P4 = new ListNode (4);
P3.next = P4;
Prinf (head);
Prinf (head) (dp.sortlist);
private static void Prinf (ListNode input) {while (input!=null) {System.out.print (input.val+ "->");
input = Input.next;
} System.out.println (); }
<span style= "White-space:pre" > </span>//under a cheap start public
listnode sortlist (ListNode head) {// Suggest you change a method name or class name, I repeat
if (head==null) return head here ;
arraylist<integer> arr = new arraylist<integer> ();
int j=0;
ListNode p= head;
while (p!=null) {
arr.add (p.val);
P=p.next;
}
object[] array = Arr.toarray ();
Arrays.sort (array);//In fact, only this step ...
ListNode start= New ListNode (0);
ListNode q = start;
for (int i=0;i<array.length;i++) {
q.val= (Integer) array[i];
if (i==array.length-1) {q.next = null;break;}
ListNode k = new ListNode (0);
q.next=k;
q=k;
}
return start
}
}