题解
链表的归并排序,注意怎么二分,比较简单。
Code
class Solution {
public ListNode sortList(ListNode head) {
if(head==null || head.next == null) return head;
ListNode pre=null,slow,fast;
slow=head;
fast=head;
while(fast!=null && fast.next!=null){ // 取中点
pre=slow;
slow=slow.next;
fast=fast.next.next;
}
pre.next=null;// 截断 中点之前
return merge(sortList(head),sortList(slow));// slow 是中点
}
public ListNode merge(ListNode l1,ListNode l2){
ListNode l=new ListNode(0), p = l;
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 l.next;
}
}