class Solution {
public ListNode sortList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode dummy = new ListNode(-1);
dummy.next = head;
int length = 0;
while(head != null){
length++;
head = head.next;
}
head = dummy.next;
for(int i = 1;i < length; i += i){
ListNode succ = dummy;
ListNode first = null;
ListNode second = null;
while(head != null){
first = head;
head = cutFromHead(head,i);
second = head;
head = cutFromHead(head,i);
succ.next = mergeLists(first,second);
while(succ.next != null) succ = succ.next;
}
head = dummy.next;
}
return dummy.next;
}
public ListNode cutFromHead(ListNode head,int n){
while(head != null && --n > 0){
head = head.next;
}
if(head == null) return null;
ListNode next = head.next;
head.next = null;
return next;
}
public ListNode mergeLists(ListNode first,ListNode second){
if(first == null) return second;
if(second == null) return first;
ListNode dummy = new ListNode(-1);
ListNode succ = dummy;
while(first != null && second != null){
if(first.val < second.val){
succ.next = first;
first = first.next;
}else{
succ.next = second;
second = second.next;
}
succ = succ.next;
}
succ.next = first != null? first : second;
return dummy.next;
}
}