给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。
示例 1:
输入: head = [4,2,1,3]
输出: [1,2,3,4]
示例 2:
输入: head = [-1,5,3,4,0]
输出: [-1,0,3,4,5]
示例 3:
输入: head = []
输出: []
提示:
- 链表中节点的数目在范围
[0, 5 * 104]内 -105 <= Node.val <= 105
进阶: 你可以在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序吗?
题解:
class Solution {
//归并排序
public ListNode sortList(ListNode head) {
return meregeSort(head,null);
}
public ListNode meregeSort(ListNode head,ListNode tail){
if(head==null) return head;
if(head.next==tail){
head.next=null;
return head;
}
ListNode fast=head,slow=head;
while(fast!=tail){
slow=slow.next;
fast=fast.next;
if(fast!=tail)
fast=fast.next;
}
ListNode temp1=meregeSort(head,slow);
ListNode temp2=meregeSort(slow,tail);
return merge(temp1,temp2);
}
public ListNode merge(ListNode temp1,ListNode temp2){
ListNode dummy=new ListNode(0);
ListNode p=dummy;
while(temp1!=null&&temp2!=null){
if(temp1.val<temp2.val){
p.next=temp1;
temp1=temp1.next;
p=p.next;
}else{
p.next=temp2;
temp2=temp2.next;
p=p.next;
}
}
if(temp1==null) p.next=temp2;
if(temp2==null) p.next=temp1;
return dummy.next;
}
}