Sort a linked list in O(n log n) time using constant space complexity.
这道题跟Insertion Sort List类似,要求我们用O(nlogn)算法对链表进行排序,但是并没有要求用哪一种排序算法,我们可以使用归并排序,快速排序,堆排序等满足要求的方法来实现。对于这道题比较容易想到的是归并排序,因为我们已经做过Merge Two Sorted Lists,这是归并排序的一个subroutine。剩下我们需要做的就是每次找到中点,然后对于左右进行递归,最后用Merge Two Sorted Lists把他们合并起来。代码如下:
public ListNode sortList(ListNode head) { return mergeSort(head); } private ListNode mergeSort(ListNode head) { if(head == null || head.next == null) return head; ListNode walker = head; ListNode runner = head; while(runner.next!=null && runner.next.next!=null) { walker = walker.next; runner = runner.next.next; } ListNode head2 = walker.next; walker.next = null; ListNode head1 = head; head1 = mergeSort(head1); head2 = mergeSort(head2); return merge(head1, head2); } private ListNode merge(ListNode head1, ListNode head2) { ListNode helper = new ListNode(0); helper.next = head1; ListNode pre = helper; while(head1!=null && head2!=null) { if(head1.val<head2.val) { head1 = head1.next; } else { ListNode next = head2.next; head2.next = pre.next; pre.next = head2; head2 = next; } pre = pre.next; } if(head2!=null) { pre.next = head2; } return helper.next; }
walker.next = null; -->为了下次的分割,
pre = pre.next; --> 为了找到拼接的位置
链表的拼接, 先记住后面的节点, 先拼接后面的节点, 不然不好表示
ListNode next = head2.next; head2.next = pre.next; pre.next = head2;