文章目录
在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
思路
(1)递归解法。
1)首先利用快慢指针定位到中间位置,直接遍历过去。
2)两个链表一直往下层递归一直到递归终止条件结束。
3)一层层的合并两个排序好的链表。
4)返回结点。
解法1-递归的归并排序-AC
class Solution {
public ListNode sortList(ListNode head) {
if (head == null || head.next == null){
return head;
}
ListNode fast = head.next, slow = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode temp = slow.next;
slow.next = null;
ListNode left = sortList(head);
ListNode right = sortList(temp);
ListNode root = new ListNode(0);
ListNode root2 = root;
// merge two list
while (left != null && right != null) {
if (left.val < right.val) {
root.next = left;
left = left.next;
} else {
root.next = right;
right = right.next;
}
root = root.next;
}
//special
root.next = left != null ? left : right;
return root2.next;
}
}