Sort a linked list in O(n log n) time using constant space complexity.
1 Packagesortlist;2 3 ImportJava.util.Iterator;4 5 classListNode {6 7 intVal;8 ListNode Next;9ListNode (intval) {Ten This. val =Val; One } A } - - Public classSolution { the Public StaticListNode sortlist (ListNode head) { - - if(Head = =NULL|| Head.next = =NULL) { - returnhead; + } - /** + * Define two pointers, one of which is twice times the other, A * When the previous one arrives at the end of the list, the next one reaches the middle of the list at */ -ListNode before =Head.next; -ListNode after =head; - while(Before.next! =NULL&& Before.next.next! =NULL) { -Before =Before.next.next; -after =After.next; in } - toListNode L2 =sortlist (after.next); +After.next =NULL; -ListNode L1 =Sortlist (head); the * returnmerge (L1, L2); $ Panax Notoginseng } - the Staticlistnode Merge (ListNode list1, ListNode list2) { + A /** the * Initialize an empty list first + * and give a node in List1 and List2 - */ $ListNode list =NULL; $ if(List1.val <=list2.val) { -List =List1; -List1 =List1.next; the}Else { -List =List2;WuyiList2 =List2.next; the } -ListNode lis =list; Wu while(List1! =NULL&& List2! =NULL) { - if(List1.val <=list2.val) { AboutLis.next =List1; $List1 =List1.next; -Lis =Lis.next; -}Else { -Lis.next =List2; AList2 =List2.next; +Lis =Lis.next; the } - } $ if(List1 = =NULL) { theLis.next =List2; the}Else { theLis.next =List1; the } - returnlist; in } the the Public Static voidMain (string[] args) { AboutListNode list =NewListNode (73); theListNode List1 =NewListNode (11); theListNode List2 =NewListNode (25); theListNode List3 =NewListNode (34); +ListNode List4 =NewListNode (18); -List.next =List1; theList1.next =List2;BayiList2.next =List3; theList3.next =List4; theListNode llll =sortlist (list); - //System.out.println (llll.next.next.val); - while(Llll! =NULL) { the System.out.println (llll.val); theLlll =Llll.next; the } the //System.out.println (llll.tostring ()); - } the the}
Merge sort of one-way list (Java)