题目地址:
https://leetcode.com/problems/sort-list/
对一个链表排序。可以使用归并排序。
public class Solution {
public ListNode sortList(ListNode head) {
if (head == null) {
return null;
}
return mergeSort(head);
}
private ListNode mergeSort(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode l1 = head;
// 这里的mid取的是整个链表的中点,如果链表长为偶数则取的是靠前的中点
ListNode mid = findMid(head);
ListNode l2 = mid.next;
// 要将链表从中间断开,才能继续归并排序
mid.next = null;
ListNode list1 = mergeSort(l1);
ListNode list2 = mergeSort(l2);
ListNode dummy = new ListNode(0);
ListNode cur = dummy;
while (list1 != null || list2 != null) {
if (list1 == null) {
cur.next = list2;
break;
}
if (list2 == null) {
cur.next = list1;
break;
}
if (list1.val <= list2.val) {
cur.next = list1;
list1 = list1.next;
} else {
cur.next = list2;
list2 = list2.next;
}
cur = cur.next;
}
return dummy.next;
}
private ListNode findMid(ListNode head) {
if (head == null) {
return null;
}
ListNode slow = head, fast = head;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
时间复杂度。
来源:CSDN
作者:edWard的算法世界
链接:https://blog.csdn.net/qq_46105170/article/details/103955989