/**
* 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) return head;
// 将小于划分点的值存储在临时链表中
ListNode newHead=new ListNode(-1);
// partition为划分点,p为链表指针,tp为临时链表指针
ListNode partition=head.next;
ListNode curr=partition;
ListNode newTail=newHead;
// 将小于划分点的结点放到临时链表中
while (curr.next!=end){
if (curr.next.val<partition.val){
newTail.next=curr.next;
newTail=newTail.next;
curr.next=curr.next.next;
}else {
curr=curr.next;
}
}
// 合并临时链表和原链表,将原链表接到临时链表后面即可
newTail.next=head.next;
// 将临时链表插回原链表,注意是插回!(不做这一步在对右半部分处理时就断链了)
head.next=newHead.next;
quickSort(head, partition);
quickSort(partition, end);
// 题目要求不带头节点,返回结果时去除
return head.next;
}
}