[LeetCode 148] Sort List
/*** Sort a linked list in O (n log n) time using constant space complexity. **/public class SortList {public class ListNode {int val; ListNode next; ListNode (int x) {val = x; next = null ;}// solution 1: merge method // 15/15 test cases passed. // Status: Accepted // Runtime: 310 MS // Submitted: 0 minutes ago // time complexity O (n * log (n) space complexity O (1) public ListNode sortList (ListNode head) {if (head = null | head. next = null ){ Return head;} ListNode slow = head; ListNode fast = head; // locate the midpoint position of the linked list while (fast. next! = Null & fast. next. next! = Null) {fast = fast. next. next; slow = slow. next;} fast = slow. next; // disconnect the linked list slow. next = null; ListNode list1 = sortList (head); ListNode list2 = sortList (fast); return mergeList (list1, list2 );} // merge two linked lists: public ListNode mergeList (ListNode head1, ListNode head2) {ListNode head = new ListNode (-1); ListNode last = head; while (head1! = Null & head2! = Null) {if (head1.val <= head2.val) {last. next = head1; head1 = head1.next;} else {last. next = head1; head1 = head1.next;} last = last. next;} if (head1! = Null) last. next = head1; if (head2! = Null) last. next = head2; return head. next;} // solution 2 // 15/15 test cases passed. // Status: Accepted // Runtime: 709 MS // Submitted: 0 minutes ago // set a midpoint pointer for the sorted linked list. If the node to be sorted is greater than the value of the midpoint pointer, then start to look for the insert point from the vertex, or start to look for it from the header // In fact, it does not reduce the time complexity as it is still O (n * n) space complexity O (1) public ListNode sortList1 (ListNode head) {ListNode preHead = new ListNode (-1); ListNode last = null; ListNode cur = null; int preNum = 0, postNum = 0; while (hea D! = Null) {ListNode headNext = head. next; if (last! = Null & last. val <= head. val) {postNum ++; cur = last;} else {preNum ++; cur = preHead;} while (cur. next! = Null) {if (cur. next. val> = head. val) {break;} cur = cur. next;} if (last = null) {last = head;} ListNode curNext = cur. next; cur. next = head; cur. next. next = curNext; head = headNext; if (postNum> preNum) {last = last. next;} return preHead. next;} public static void main (String [] args) {// TODO Auto-generated method stub }}