给你链表的头结点 head
,请将其按 升序 排列并返回 排序后的链表 。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode sortList(ListNode head) {
if(head==null||head.next==null){ //链表为空或者只有一个元素
return head;
}
ListNode newHead=new ListNode(-1); //创建一个头节点,最后去掉即可
newHead.next=head;
return quickSort(newHead,null);
}
private ListNode quickSort(ListNode head,ListNode end){ //快排
if(head==end||head.next==end||head.next.next==end){ //考虑边界情况
return head;
}
ListNode tmpHead=new ListNode(-1);
ListNode povit=head.next,p=povit,tp=tmpHead;//povit为划分点,p为链表指针,tp为临时链表指针
while(p.next!=end){ //将小于划分点的结点放到临时链表中
if(p.next.val<povit.val){
tp.next=p.next;
tp=tp.next;
p.next=p.next.next;
}else{
p=p.next;
}
}
tp.next=head.next;// 合并临时链表和原链表,将原链表接到临时链表后面即可
head.next=tmpHead.next;// 将临时链表插回原链表,注意是插回!
quickSort(head,povit);
quickSort(povit,end);
return head.next;//返回结果时去除头节点
}
}
时间复杂度O(nlogn)
空间复杂度O(1)