排序链表
1 题目地址
https://leetcode-cn.com/problems/sort-list/
2 题目描述
在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
示例 1:
输入: 4->2->1->3
输出: 1->2->3->4
示例 2:
输入: -1->5->3->4->0
输出: -1->0->3->4->5
3 思路
归并排序,快慢指针进行链表的分割, 把分割后的链表进行排序,最后归并。
public static ListNode sortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode fast = head;
ListNode slow = head;
while (fast.next != null) {
fast = fast.next.next;
if (fast == null) {
break;
}
slow = slow.next;
}
ListNode subNode = slow.next;
slow.next = null;
ListNode left = sortList(head);
ListNode right = sortList(subNode);
return merge(left, right);
}
private static ListNode merge(ListNode left, ListNode right) {
ListNode head = new ListNode(-1);
ListNode curNode = head;
while (left != null && right != null) {
if (left.val > right.val) {
curNode.next = new ListNode(right.val);
right = right.next;
} else {
curNode.next = new ListNode(left.val);
left = left.next;
}
curNode = curNode.next;
}
if (left != null) {
curNode.next = left;
}
if (right != null) {
curNode.next = right;
}
return head.next;
}