在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
示例 1:
输入: 4->2->1->3
输出: 1->2->3->4
示例 2:
输入: -1->5->3->4->0
输出: -1->0->3->4->5
Java代码:
class Solution {
public ListNode sortList(ListNode head) {
if (null == head || null == head.next)
return head;
// 仅包含两个节点
if (null == head.next.next) {
ListNode p = head, q = head.next;
if(p.val > q.val) {
head = q;
q.next = p;
p.next = null;
}
return head;
}
// 将链表拆分为前后两部分,分别排序后合并
ListNode fast = head, slow = head;
while (null != fast && null != fast.next) {
slow = slow.next;
fast = fast.next.next;
}
ListNode head2 = slow.next, list1, list2;
slow.next = null;
list1 = sortList(head);
list2 = sortList(head2);
head = merge(list1, list2);
return head;
}
private ListNode merge(ListNode head1, ListNode head2) {
if (null == head1 && null == head2)
return null;
if (null == head1 || null == head2)
return null == head1 ? head2 : head1;
ListNode p = head1.val <= head2.val ? head1 : head2, q = p == head1 ? head2 : head1, head = p, cur = head;
while (null != p && null != q) {
if (p.val <= q.val) {
cur = p;
p = p.next;
} else {
cur.next = q;
cur = q;
ListNode tmp = q.next;
q.next = p;
q = tmp;
}
}
if (null != p)
cur.next = p;
if (null != q)
cur.next = q;
return head;
}
}