Sort a linked list in O(n log n) time using constant space complexity.
public class Solution {
public ListNode sortList(ListNode head) {
if(head==null||head.next==null){
return head;
}
ListNode fast=head;
ListNode slow=head;
while(fast.next!=null&&fast.next.next!=null){
slow=slow.next;
fast=fast.next.next;
}
fast=slow.next;
slow.next=null;
ListNode h1= sortList(head);
ListNode h2=sortList(fast);
return merge(h1,h2);
}
public static ListNode merge(ListNode h1,ListNode h2){
ListNode head=null;
ListNode tail=null;
while(h1!=null&&h2!=null){
ListNode node;
if(h1.val<h2.val){
node=new ListNode(h1.val);
h1=h1.next;
}else{
node=new ListNode(h2.val);
h2=h2.next;
}
head=head==null?node:head;
if(tail!=null){
tail.next=node;
}
tail=node;
}
tail.next=h1!=null?h1:h2;
return head;
}
}