Node* MergeSort(Node* head)
{
if(head==NULL || head->next==NULL) return head;
Node* fast=head, *slow=head;
while(fast->next&&fast->next->next)
{
fast=fast->next->next;
slow=slow->next;
}
fast=slow->next;
slow->next=NULL;
slow=MergeSort(head);
fast=MergeSort(fast);
return MSort(slow, fast);
}
Node* MSort(Node* left,Node* right)
{
Node head;
Node *end=&head;
while(left&&right)
{
if(left->val<right->val)
{
end->next=left;
left=left->next;
}
else
{
end->next=right;
right=right->next;
}
end=end->next;
}
if(left)
{
end->next=left;
}
if(right)
{
end->next=right;
}
return head.next;
}