思路 使用归并排序
public class Solution{
public ListNode sortList(ListNode head){
//终止条件
if(head==null||head.next==null)
return head;
ListNode prev = null,slow=head,fast=head;
//分为前后两部分
while(fast!=null&&fast.next!=null){
prev = slow;
slow = slow.next;
fast = fast.next.next;
}
prev.next = null;
//分别对前后两部分进行排序
ListNode l1 = sortList(head);
ListNode l2 = sortList(slow);
//对两部分进行合并
return merge(l1,l2);
}
ListNode merge(ListNode l1,ListNode l2){
ListNode dummyHead = new ListNode(0),p=dummyHead;
//合并的过程
while(l1!=null&&l2!=null){
if(l1.val<l2.val){
p.next = l1;
l1 = l1.next;
}else{
p.next = l2;
l2 = l2.next;
}
p = p.next;
}
if(l1!=null)
p.next = l1;
if(l2!=null)
p.next = l2;
return dummyHead.next;
}
}