/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode sortList(ListNode head) {
ListNode fast=head, slow=head;
if(fast == null || fast.next == null)
return head;
while(fast.next != null && fast.next.next != null){
fast=fast.next.next;
slow=slow.next;
}
ListNode head2 = slow.next;
slow.next=null;
ListNode l1 = sortList(head);
ListNode l2 = sortList(head2);
return mergeList(l1,l2);
}
private ListNode mergeList(ListNode l1, ListNode l2){
ListNode nd = new ListNode(-1);
ListNode p = nd;
while(l1!=null && l2!=null){
if( v1 <= v2){
p.next = l1;
l1 = l1.next;
}else{
p.next = l2;
l2 = l2.next;
}
p = p.next;
}
p.next = l1!=null? l1: l2;
return nd.next;
}
}
分析: nlogn的要求,就要确定一般的排序肯定不行。单向链表用归并,双向链表用快排。 tricky的地方:快慢指针找中间点;mergelist返回总是排序完成之后的head.
Sort a linked list in O(n log n)
time using constant space complexity.