![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/783515e3c937bf547964c5521aab72da.png)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/4858c0f9a2a4b560616b7eec5d2b316c.png)
官方
class Solution {
public ListNode sortList(ListNode head) {
return sortList(head, null);
}
public ListNode sortList(ListNode head, ListNode tail) {
if (head == null) {
return head;
}
if (head.next == tail) {
head.next = null;
return head;
}
ListNode slow = head, fast = head;
while (fast != tail && fast.next != tail) {
slow = slow.next;
fast = fast.next.next;
}
ListNode mid = slow;
ListNode list1 = sortList(head, mid);
ListNode list2 = sortList(mid, tail);
ListNode sorted = merge(list1, list2);
return sorted;
}
public ListNode merge(ListNode head1, ListNode head2) {
ListNode dummyHead = new ListNode(0);
ListNode temp = dummyHead, temp1 = head1, temp2 = head2;
while (temp1 != null && temp2 != null) {
if (temp1.val <= temp2.val) {
temp.next = temp1;
temp1 = temp1.next;
} else {
temp.next = temp2;
temp2 = temp2.next;
}
temp = temp.next;
}
if (temp1 != null) {
temp.next = temp1;
} else if (temp2 != null) {
temp.next = temp2;
}
return dummyHead.next;
}
}
快速排序链表
class Solution {
public ListNode sortList(ListNode head) {
quickSort(head, null);
return head;
}
void quickSort(ListNode head, ListNode tail){
if(head == tail || head.next == tail) return;
int pivot = head.val;
ListNode left = head, cur = head.next;
while(cur != tail){
if(cur.val < pivot){
left = left.next;
swap(left, cur);
}
cur = cur.next;
}
swap(head, left);
quickSort(head, left);
quickSort(left.next, tail);
}
public void swap(ListNode head, ListNode left){
int tmp = head.val;
head.val = left.val;
left.val = tmp;
}
}
class Solution {
public ListNode sortList(ListNode head) {
ListNode newList = partition(head);
return newList;
}
public ListNode partition(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode left = new ListNode(0), ll = left;
ListNode right = new ListNode(0), rr = right;
ListNode base = head;
int baseVal = base.val;
ListNode cur = head.next;
while (cur != null) {
ListNode next = cur.next;
cur.next = null;
if (cur.val < baseVal) {
ll.next = cur;
ll = ll.next;
} else {
rr.next = cur;
rr = rr.next;
}
cur = next;
}
left.next = partition(left.next);
right.next = partition(right.next);
cur = left;
while (cur.next != null) {
cur = cur.next;
}
cur.next = base;
base.next = right.next;
return left.next;
}
}