Topic Description 1 Singly Linked List Sorting Problem
Sort a linked list in O(n log n) time using constant space complexity.
With merge sort: where only a preHead node is created takes space O(1) time O(nlogn)
public class Solution { public ListNode sortList(ListNode head) { if(head == null || head.next == null) { return head; } //Conventional merge sort idea ListNode mid = getMid(head); ListNode midNext = mid.next; mid.next = null; //Be sure to disconnect the tail of the linked list in the left half of the head return mergeSort (sortList (head), sortList (midNext)); } private ListNode getMid(ListNode head) { //Use the fast and slow pointer to get the position of the middle node 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) { Merge two sub-linked lists ListNode preHead = new ListNode(0), cur1 = n1, cur2 = n2, 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; } cur.next = cur1 == null ? cur2 : cur1; //See which linked list is not empty and continue to connect return preHead.next; } }
Use quicksort:
public class Solution { public ListNode sortList(ListNode head) { quickSort(head, null); //head and tail nodes return head; } public static void quickSort(ListNode head, ListNode end) { if(head != end) { ListNode
partition= partition(head);quickSort(head, partition); //分解成两部分 quickSort(partition.next, end); } } public static ListNode partition(ListNode head) { ListNode slow = head; ListNode fast = head.next; while (fast != null) { if(fast.val < head.val) { slow = slow.next; fast.val = slow.val ^ fast.val ^ (slow.val = fast.val); } fast = fast.next; } slow.val = head.val ^ slow.val ^ (head.val = slow.val); return slow; }}