排序鏈表
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;
}