Sort a linked list in O(n log n) time using constant space complexity.
分析:对链表进行排序,如果是单链表用归并排序时最快的,并且在对数组进行归并的时候是需要用到O(n)的空间的,但是链表就不需要了,只要有O(1)的空间就够了,因为不需要辅助变量来存储。
首先是递归的将链表拆分开,然后将链表进行合并。
下面是代码:
<span style="font-family:Helvetica Neue, Helvetica, Arial, sans-serif;color:#333333;">public ListNode sortList(ListNode head){
if(head == null || head.next == null)
return head;
//find the middle node
ListNode fast = head,slow = head;
while(fast.next != null && fast.next.next != null){
fast = fast.next.next;
slow = slow.next;
}
//diconnect the List
fast = slow;
slow = slow.next;
fast.next = null;
//Recursive
ListNode l1 = sortList(head);
ListNode l2 = sortList(slow);
//Meger the List
return MegerList(l1,l2);
}
public ListNode MegerList(ListNode l1,ListNode l2){
ListNode head = new ListNode(-1);
for(ListNode p = head;l1 != null || l2 != null; p = p.next){
int val1 = l1 == null?Integer.MAX_VALUE:l1.val;
int val2 = l2 == null?Integer.MAX_VALUE:l2.val;
if(val1 <= val2){
p.next = l1;
l1 = l1.next;
}else{
p.next = l2;
l2 = l2.next;
}
}
return head.next;
}</span>