Leetcode148. 排序链表
题目:
在
O
(
n
l
o
g
n
)
O(n log n)
O(nlogn) 时间复杂度和常数级空间复杂度下,对链表进行排序。
示例 1:
输入: 4->2->1->3
输出: 1->2->3->4
示例 2:
输入: -1->5->3->4->0
输出: -1->0->3->4->5
题解:
归并排序+递归
java代码:
/**
* @param head
* @return
*/
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.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode tmp = slow.next;
slow.next = null;
ListNode left = sortList(head);
ListNode right = sortList(tmp);
ListNode dummy = new ListNode(-1);
ListNode res = dummy;
while (left != null && right != null) {
if (left.value < right.value) {
res.next = left;
left = left.next;
} else {
res.next = right;
right = right.next;
}
res = res.next;
}
if (left != null) {
res.next = left;
} else {
res.next = right;
}
return dummy.next;
}