标签:next head log link fast java output slow 思路
??Medium
Sort a linked list in O(n log n) time using constant space complexity.
Example 1:
Input: 4->2->1->3
Output: 1->2->3->4
Example 2:
Input: -1->5->3->4->0
Output: -1->0->3->4->5
??对链表进行归并排序,时间复杂为O(nlgn),空间复杂度为O(1)。
public class Solution{
public ListNode sortList(ListNode head){
if(head==null||head.next=null)
return head;
ListNode slow=head;
ListNode fast=head;
while(fast.next!=null&&fast.next.next!=null){
slow=slow.next;
fast=fast.next.next;
}
ListNode right=slow.next;
slow.next=null;//将左右链表断开
return merge(sortList(head),sortList(right));
}
public ListNode merge(ListNode head,ListNode right){
if(head==null)
return right;
if(right==null)
return head;
ListNode pHead=new ListNode(0);
if(head.val<right.val){
pHead=head;
pHead.next=merge(head.next,right);
}else{
pHead=right;
pHead.next=merge(head,right.next);
}
return pHead;
}
}
标签:next head log link fast java output slow 思路
原文地址:https://www.cnblogs.com/yjxyy/p/11080420.html