Title:
In the O(n log n) time, we use constant level space complexity to sort the linked list.
Ideas:
Because the complexity of the topic is O(nlogn), the idea of merging and sorting can be considered.
The general steps of merging and sorting are as follows:
1) Take the middle point of the array (linked list) to be sorted and divide it into two parts;
2) The left part is sorted recursively;
3) The right part is sorted recursively;
4) merge the two halves to get the result.
So corresponding to this topic, it can be divided into three small problems:
1) Find the middle point of the list (fast pointer idea, fast pointer goes two steps at a time, slow pointer goes one step at a time, when fast pointer is at the end of the list, slow pointer happens to be at the middle point of the list);
2) Write the merge function, that is, how to merge the linked list. (see the analysis of merge two sorted lists)
3) Write the mergeport function to implement the above steps.
code:
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode sortList(ListNode head) { if(head == null || head.next == null) { return head; } ListNode mid = getMid(head); ListNode midNext = mid.next; mid.next = null; return mergeSort(sortList(head), sortList(midNext)); } private ListNode getMid(ListNode head) { if(head == null || head.next == null) { return head; } ListNode slow = head, quick = head; while(quick.next != null && quick.next.next != null) { slow = slow.next; quick = quick.next.next; } return slow; } private ListNode mergeSort(ListNode n1, ListNode n2) { ListNode preHead = new ListNode(0); ListNode cur1 = n1; ListNode cur2 = n2; ListNode cur = preHead; while(cur1 != null && cur2 != null) { if(cur1.val < cur2.val) { cur.next = cur1; cur1 = cur1.next; } else { cur.next = cur2; cur2 = cur2.next; } cur = cur.next; } if(cur1 != null){ cur.next = cur1; } if(cur2 != null){ cur.next = cur2; } return preHead.next; } }