Sort a linked list in O(n log n) time using constant space complexity.
考虑到时间复杂度为O(nlogn)的排序算法有:快速排序,归并排序,堆排序和希尔排序,而适合用链表实现的应该是归并排序
归并排序算法介绍:
归并排序的一般步骤为:
1)将待排序数组(链表)取中点并一分为二;
2)递归地对左半部分进行归并排序;
3)递归地对右半部分进行归并排序;
4)将两个半部分进行合并(merge),得到结果。
所以对应此题目,可以划分为三个小问题:
1)找到链表中点 (快慢指针思路,快指针一次走两步,慢指针一次走一步,快指针在链表末尾时,慢指针恰好在链表中点);
2)写出merge函数,即如何合并链表。
3)写出 sortList
函数,实现上述步骤。
例子:
动画演示实例:
对6 5 3 1 8 7 24 进行合并排序的动画效果如下:
java代码实现:
package code.sortList;
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode sortList(ListNode head) {
if(head==null || head.next==null){
return head;
}
ListNode part1=getMiddlePos(head);
ListNode part2=part1.next;
part1.next=null;//注意截断链表
return merge(sortList(head),sortList(part2));
}
public ListNode getMiddlePos(ListNode head){
ListNode low=head;
ListNode fast=head;
if(head==null || head.next==null){
return head;
}
while(fast.next!=null && fast.next.next!=null){//注意限定边界条件,这里出错容易越界
low=low.next;
fast=fast.next.next;
}
return low;
}
public ListNode merge(ListNode head1,ListNode head2){
ListNode out=new ListNode(0);
ListNode temp=out;
while(head1!=null && head2!=null){
if(head2.val<head1.val){
temp.next=head2;
head2=head2.next;
}else{
temp.next=head1;
head1=head1.next;
}
temp=temp.next;
}
if(head1!=null){
temp.next=head1;
}
if(head2!=null){
temp.next=head2;
}
return out.next;
}
public static void main(String args[]){
int data[]={7,3,8,7,9,1,6,2,10};
Solution s=new Solution();
ListNode head=new ListNode(data[0]);
ListNode temp=head;
for(int i=1;i<data.length;i++){
temp.next=new ListNode(data[i]);
temp=temp.next;
}
head=s.sortList(head);
int out[]=new int[data.length];
int mm=0;
while(head!=null){
out[mm]=head.val;
mm++;
head=head.next;
}
for(int i=0;i<out.length;i++){
System.out.print(out[i]+" ");
}
}
}