一,题目描述
public class Solution {
/**
* 归并排序
* @param head ListNode类 the head node
* @return ListNode类
*/
public ListNode sortInList (ListNode head) {
if(head==null||head.next==null){
return head;
}
// write code here
ListNode slow=head;
ListNode fast=head.next;//保证fast走到底的时候slow走到中间
while(fast!=null&&fast.next!=null){
fast=fast.next.next;
slow=slow.next;
}
//讲链表分成两部分
ListNode tmp=slow.next;
slow.next=null;
ListNode left=sortInList(head);
ListNode right=sortInList(tmp);
ListNode res= new ListNode(0);
ListNode res1=res;
while(left!=null&&right!=null){
if(left.val<right.val){
res.next=left;
res=res.next;
left=left.next;
}else{
res.next=right;
res=res.next;
right=right.next;
}
}
res.next=left==null?right:left;
return res1.next;
}
}