Sort a linked list in O(n log n) time using constant space complexity.
思路: 利用归并排序的思想,每一次采用快慢指正找出链表的中点,将中点左边的链表进行排序,然后中点右边的链表进行排序,最后将排好序的左右两边的链表进行归并。
public class Solution {
public ListNode sortList(ListNode head) {
if(head==null || head.next==null) return head;
ListNode mid=getMid(head);
ListNode next=mid.next;
mid.next=null;
//将中点左边的链表进行排序
ListNode left=sortList(head);
//将中点右边的链表进行排序
ListNode right=sortList(next);
//返回归并后的链表
return mergeList(left,right);
}
//采用快慢指针找出链表的中点,slow每一次走一步,fast每次走两步,当fast走到末尾的时候,slow所在的地方就是该链表的中点
ListNode getMid(ListNode head)
{
ListNode slow=head;
ListNode fast=head;
while( fast.next!=null && fast.next.next!=null )
{
slow=slow.next;
fast=fast.next;
fast=fast.next;
}
return slow;
}
//归并两个链表
public ListNode mergeList(ListNode head1,ListNode head2)
{
ListNode head=new ListNode(-1);
ListNode last=head;
while(head1!=null && head2!=null)
{
if(head1.val<=head2.val)
{
last.next=head1;
last=last.next;
head1=head1.next;
}else {
last.next=head2;
last=last.next;
head2=head2.next;
}
}
if(head1!=null)
last.next=head1;
else if(head2!=null)
last.next=head2;
return head.next;
}
}