Sort list
Sort a linked list inO(NLogN) Time using constant space complexity.
Algorithm idea:
The time complexity is O (nlogn) sorting algorithms, such as fast sorting, Merge Sorting, and heap sorting. The fast sorting needs to be traversed forward. Therefore, it is not suitable for single-chain tables, and heap sorting is acceptable, however, the space of O (n) is required, so the best answer to this question should be the merge order.
It is consistent with the merge sort idea of array.
The Code is as follows:
1 public class Solution { 2 public ListNode sortList(ListNode head) { 3 if(head == null || head.next == null) return head; 4 ListNode hhead = new ListNode(0); 5 hhead.next = head; 6 ListNode fast = hhead; 7 ListNode slow = hhead; 8 while(fast != null && fast.next != null){ 9 fast = fast.next.next;10 slow = slow.next;11 }12 ListNode right = slow.next;13 slow.next = null;14 ListNode left = sortList(head);15 right = sortList(right);16 return merge(left, right);17 }18 private ListNode merge(ListNode l1,ListNode l2){19 ListNode hhead = new ListNode(0);20 hhead.next = l1;21 ListNode p = hhead;22 while(p.next != null){23 if(p.next.val > l2.val){24 ListNode tem = l2;25 l2 = l2.next;26 tem.next = p.next;27 p.next = tem;28 }else29 p = p.next;30 if(l2 == null) return hhead.next;31 }32 p.next = l2;33 return hhead.next;34 }35 }