1. 问题描述
在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
示例 1:
输入: 4->2->1->3 输出: 1->2->3->4
示例 2:
输入: -1->5->3->4->0 输出: -1->0->3->4->5
2. 代码实现
链表排序最好用归并排序,最好最坏时间复杂度均为O(nlogn) ,且它在数组排序中广受诟病的空间复杂度在链表排序中也从O(n)降到了O(1)。
所有排序方法参考:https://www.cnblogs.com/TenosDoIt/p/3666585.html
class Solution {
public ListNode sortList(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode slow = head, fast = head;
while(fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
//划分成两段链表
fast = slow;
slow = slow.next;
fast.next = null;
fast = sortList(head);
slow = sortList(slow);
return merge(fast, slow);
}
ListNode merge(ListNode head1, ListNode head2) {
ListNode newhead = new ListNode(0);
ListNode cur = newhead;
while(head1 != null && head2 != null) {
if(head1.val <= head2.val) {
cur.next = head1;
cur = cur.next;
head1 = head1.next;
}
else {
cur.next = head2;
cur = cur.next;
head2 = head2.next;
}
}
cur.next = head1 == null ? head2 : head1;
return newhead.next;
}
}