Sort a linked list in O(n log n) time using constant space complexity.
对单链表进行排序,时间复杂度和空间复杂度决定了使用堆排序或者是快速排序。
采用的是堆排序,和数组不同的地方是需要找到中间的节点,然后递归进行分割到最下的单位,最后进行合并,合并的时候采用的是哑节点进行帮助,这样会方便的进行操作。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode sortList(ListNode head) {
if(head==null||head.next==null) return head;
ListNode slow=head,fast=head.next.next;
while(fast!=null&&fast.next!=null){
slow=slow.next;
fast=fast.next.next;
}
//找到中间的节点slow
ListNode p1=sortList(slow.next);
slow.next=null;
ListNode p2=sortList(head);
return merge(p1,p2);
}
public ListNode merge(ListNode i,ListNode j){
ListNode p,dummy=new ListNode(0);
p=dummy;
while(i!=null&&j!=null){
if(i.val<j.val){
p.next=i;
i=i.next;
}
else{
p.next=j;
j=j.next;
}
p=p.next;
}
p.next = (i==null?j:i);//合并剩余的
return dummy.next;
}
}