[leetcode] Sort List
Sort a linked list in O(n log n) time using constant space complexity.
https://oj.leetcode.com/problems/sort-list/
思路:归并排序,递归执行。
public class Solution { public ListNode sortList(ListNode head) { if(head==null||head.next==null) return head; ListNode fast =head; ListNode slow =head; while(fast!=null&&fast.next!=null&&fast.next.next!=null){ fast=fast.next.next; slow=slow.next; } ListNode one =head; ListNode two =slow.next; slow.next=null; one = sortList(one); two = sortList(two); return merge(one,two); } private ListNode merge(ListNode l1, ListNode l2){ if(l1==null) return l2; if(l2==null) return l1; ListNode dummyHead = new ListNode(-1); ListNode p =dummyHead; while(l1!=null&&l2!=null){ if(l1.val<=l2.val){ p.next =l1; l1=l1.next; } else{ p.next=l2; l2=l2.next; } p=p.next; } if(l1!=null) p.next=l1; if(l2!=null) p.next=l2; return dummyHead.next; } }
快速排序
public class Solution { public ListNode sortList(ListNode head) { ListNode p = head; while (p != null) p = p.next; quickSort(head, null); return head; } private void quickSort(ListNode from, ListNode to) { if (from != to) { ListNode p = partition(from, to); quickSort(from, p); quickSort(p.next, to); } } private ListNode partition(ListNode from, ListNode to) { int key = from.val; ListNode p = from; ListNode q = p.next; while (q != to) { if (q.val <= key) { p = p.next; int tmp = p.val; p.val = q.val; q.val = tmp; } q = q.next; } int tmp = p.val; p.val = from.val; from.val = tmp; return p; } public static void main(String[] args) { ListNode head = ListUtils.makeList(5, 4, 1, 6, 2, 1); new Solution().sortList(head); ListUtils.printList(head); Object obj; } }