Sort a linked list in O(n log n) time using constant space complexity.
tag:
链表排序
归并排序:
- 分解: 采用快慢指针找到链表中点,分解为两个子链表
- 求解: 递归求解子链表
- 合并: 合并两个有序链表
java
public ListNode sortList(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode slow = head, fast = head, pre = null;
while (fast != null && fast.next != null) {
pre = slow;
slow = slow.next;
fast = fast.next.next;
}
pre.next = null;
ListNode l1 = sortList(head), l2 = sortList(slow);
return merge(l1, l2);
}
ListNode merge(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0), p = dummy;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
p.next = l1;
l1 = l1.next;
} else {
p.next = l2;
l2 = l2.next;
}
p = p.next;
}
if (l1 != null)
p.next = l1;
if (l2 != null)
p.next = l2;
return dummy.next;
}
go