class Solution {
public:
int getlen(ListNode *head){
int cnt=0;
while(head) ++cnt,head=head->next;
return cnt;
}
ListNode* mov(ListNode*& x,int len,int flag){
ListNode *pre=NULL;
while(len--&&x) pre=x,x=x->next;
if(pre&&flag) pre->next=NULL;
return x;
}
void cat(ListNode* x,ListNode *y){
while(x->next) x=x->next;
x->next=y;
}
ListNode* merge(ListNode* x,ListNode *y){
if(!y) return x;
ListNode *head=new ListNode(),*now=head;
while(x&&y){
if(x->val<y->val) now=now->next=x,x=x->next;
else now=now->next=y,y=y->next;
}
while(x) now=now->next=x,x=x->next;
while(y) now=now->next=y,y=y->next;
return head->next;
}
ListNode* sort_dep(ListNode *x,int len){
if(!x) return NULL;
ListNode *tmpx=x;
ListNode *mid=mov(x,len,1),*y=mov(mid,len,1);
ListNode *res=merge(tmpx,x);
cat(res,y);
return res;
}
ListNode* sortList(ListNode* head) {
if(!head) return NULL;
ListNode *ans=new ListNode(),*p=ans;
ans->next=head;
for(int len=1,n=getlen(head);len<n;len<<=1){
while(p){
p->next=sort_dep(p->next,len);
mov(p,2*len,0);
}
p=ans;
}
return ans->next;
}
};
class Solution {
public:
int getlen(ListNode *x){
int cnt=0;
while(x) x=x->next,++cnt;
return cnt;
}
ListNode* merge(ListNode* x,ListNode *y){
if(!y) return x;
if(!x) return y;
ListNode *head=new ListNode(),*now=head;
while(x&&y){
if(x->val<y->val) now=now->next=x,x=x->next;
else now=now->next=y,y=y->next;
}
while(x) now=now->next=x,x=x->next;
while(y) now=now->next=y,y=y->next;
return head->next;
}
ListNode* sort(ListNode*& head,int l,int r){
if(l==r) {
ListNode *ans=head->next;
head->next=NULL;
return ans;
}
int mid=(l+r)>>1;
ListNode *rs=sort(head,l,mid);
ListNode *nex=sort(rs,mid+1,r);
head=merge(head,rs);
return nex;
}
ListNode* sortList(ListNode* head) {
if(!head) return head;
sort(head,0,getlen(head)-1);
return head;
}
};