Sort a linked list in O(n log n) time using constant space complexity.
既然要求复杂度为O(nlogn),那么要么是快速排序要么是归并排序,这里采用归并排序,需要注意mid分割点的寻找
采用快慢指针得到mid节点,然后分为两段进行排序并合并,递归进行。代码如下:
public ListNode sortList(ListNode head) {
if(head==null||head.next==null)
return head;
ListNode slow = head;
ListNode fast = head;
ListNode result = head;
ListNode pre = head;
while(fast!=null&&fast.next!=null){
pre = slow;
slow = slow.next;
fast = fast.next.next;
}
pre.next = null;
ListNode h1 = head;
ListNode h2 = slow;
//slow.next = null;
ListNode s1 = sortList(h1);
ListNode s2 = sortList(h2);
result = merge(s1,s2);
return result;
}
public static ListNode merge(ListNode h1, ListNode h2) {
if(h1==null)
return h2;
if(h2==null)
return h1;
ListNode head = null;
ListNode p = h1;
ListNode q = h2;
if(h1.val<=h2.val){
head = h1;
p = p.next;
}
else {
head = h2;
q = q.next;
}
head.next = null;
ListNode k = head;
while (p!=null && q!=null) {
if (p.val<q.val) {
k.next = p;
p = p.next;
k = k.next;
k.next = null;
} else {
k.next = q;
q = q.next;
k = k.next;
k.next = null;
}
}
if (p!=null) {
k.next = p;
}
if (q!=null) {
k.next = q;
}
return head;
}