LeetCode-148-排序链表
思路
要求时间复杂度为nlogn,那么只能考虑使用归并排序
代码
class Solution {
public ListNode sortList(ListNode head) {
if(head==null||head.next==null)return head;
ListNode fast=head.next;
ListNode slow=head;
while(fast!=null&&fast.next!=null){
fast=fast.next.next;
slow=slow.next;
}
//找到中点,进行分割
ListNode tmp=slow.next;
slow.next=null;
ListNode left=sortList(head);
ListNode right=sortList(tmp);
ListNode res=new ListNode();
ListNode h=res;
while(left!=null&&right!=null){
if(left.val<right.val){
res.next=left;
left=left.next;
}
else{
res.next=right;
right=right.next;
}
res=res.next;
}
res.next=left==null?right:left;
return h.next;
}
}