Sort List
Sort a linked list in O(n log n) time using constant space complexity.
思想: divede and conquer,利用主定理公式,复杂度为O(nlogn).先用slow和fast指针分解两个链表,第一个链表的尾部节点为null。然后用merge算法合并。
- public ListNode merge(ListNode f1,ListNode f2) {
- ListNode dummy = new ListNode(-1);
- dummy.next = f1;
- ListNode tmp=dummy;
- while(f1!=null && f2!=null) {
- if(f1.val > f2.val) {
- ListNode p=f2;
- f2=f2.next;
- tmp.next=p;
- p.next=f1;
- } else {
- f1=f1.next;
- }
- tmp=tmp.next;
- }
- if(f1==null) tmp.next=f2;
- return dummy.next;
- }
- public ListNode sortList(ListNode head) {
- if(head==null || head.next==null) return head;
- ListNode slow=head;
- ListNode fast=head;
- while(fast.next!=null) {
- fast=fast.next.next;
- if(fast==null) break;
- slow=slow.next;
- }
- ListNode second = slow.next;
- slow.next=null;
- ListNode f1 = sortList(head);
- ListNode f2 = sortList(second);
- return merge(f1,f2);
- }