Sort a linked list in O(n log n) time using constant space complexity.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
|
class Solution { public ListNode sortList(ListNode head) { if(head == null || head.next == null) return head; ListNode slow = head; ListNode fast = head; ListNode mid = null; while(fast!= null && fast.next != null){ mid = slow; slow = slow.next; fast = fast.next.next; } mid.next = null; ListNode p = sortList(head); ListNode q = sortList(slow); ListNode ans = merge(p,q); return ans; } public ListNode merge(ListNode p, ListNode q){ ListNode t = new ListNode(0); ListNode dummy = t; while(p!=null && q != null){ if(p.val < q.val){ t.next = p; p = p.next; } else{ t.next = q; q = q.next; } t = t.next; } if(p!=null) t.next = p; if(q!=null) t.next = q; return dummy.next; } }
|
- 利用并归排序实现的。
- 严格意义上来说,空间复杂度并不是O(1), 因为递归调用时,栈中同样消耗了空间。