Title: Sort A linked list in O (n log n) time using constant space complexity.
Train of thought: Require time complexity O (NLOGN)
Knowledge Points: Merge sort, link list find Midpoint method
Disadvantages of existence: the boundary condition is more consideration!!!
/** * Leetcode Sort list Sort a linked list in O (n log n) time using constant space complexity. * Title: Sorting a single linked list, time complexity requires O (NLOGN) * Ideas: 1 time complexity is O (nlog n) sorting algorithm has: merge sort, fast row (expected), heap sort * 2, single-linked list sorting with merge sort, double-linked list sorting with fast row * Definition for singly-linked list. * Class ListNode {* int val; * ListNode Next; * ListNode (int x) {* val = x; * next = NULL; * } *} */package javatrain;class ListNode {int val; ListNode Next; ListNode (int x) {val = x; next = null; }}public class Train4 {public ListNode sortlist (ListNode head) {if (head = = NULL | | head.next = = NULL) return head; ListNode fast = head; ListNode slow = Head;while (Fast.next.next! = NULL && Slow.next! = null) {fast = fast.next.next;//makes a point to the middle after traversing the list One point to the end, that is to find the list midpoint slow = Slow.next;} ListNode List2 = Slow.next;slow.next = Null;head = Sortlist (head); list2 = Sortlist (list2); return merge (HEAD,LIST2);} private static ListNode merge (ListNode List1,listnode list2) {if (List1 = = null) return List2; if (list2 = = null) return list1; ListNode head = new ListNode (0); ListNode last = head; while (List1.next = null && list2.next! = null) {if (List1.val <= list2.val) {last.next = List1;list1 = List1.next ;} Else{last.next = List2;list2 = List2.next;} last = Last.next;} if (list1! = null) Last.next = List1;else if (list2! = null) Last.next = List2;return Head.next;}}
"Leetcode" sort list single-linked list merge sorting