题目来源
题目描述
给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。
进阶:
你可以在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序吗?
思路分析
题目解答
class Solution {
public ListNode sortList(ListNode head) {
return sortList(head,null);
}
public ListNode sortList(ListNode head,ListNode tail){
if(head==null){
return null;
}
if(head.next==tail){
head.next=null;
return head;
}
ListNode fast=head;
ListNode slow=head;
while(fast!=tail){
fast=fast.next;
slow=slow.next;
if(fast!=tail){
fast=fast.next;
}
}
ListNode mid=slow;
ListNode l1=sortList(head,mid);
ListNode l2=sortList(mid,tail);
ListNode sorted=merge(l1,l2);
return sorted;
}
public ListNode merge(ListNode l1,ListNode l2){
if(l1==null){
return l2;
}
if(l2==null){
return l1;
}
ListNode cur1=l1;
ListNode cur2=l2;
ListNode newHead=new ListNode(-1);
ListNode newTail=newHead;
while(cur1!=null&&cur2!=null){
if(cur1.val<cur2.val){
newTail.next=cur1;
newTail=newTail.next;
cur1=cur1.next;
}else{
newTail.next=cur2;
newTail=newTail.next;
cur2=cur2.next;
}
}
if(cur1==null){
newTail.next=cur2;
}
if(cur2==null){
newTail.next=cur1;
}
return newHead.next;
}
}