在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
示例 1:
输入: 4->2->1->3
输出: 1->2->3->4
public class SortList {
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public ListNode sortList(ListNode head) {
if (head == null) {
return head;
}
return mergeSort(head);
}
public ListNode mergeSort(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode pre = null;
ListNode mid = head;
ListNode right = head;
while (right != null && right.next != null) {
pre = mid;
mid = mid.next;
right = right.next.next;
}
pre.next = null;
ListNode l = mergeSort(head);
ListNode r = mergeSort(mid);
return merge(l, r);
}
private ListNode merge(ListNode l, ListNode r) {
ListNode tmpHead = new ListNode(-1);
ListNode cur = tmpHead;
while (l != null && r != null) {
if (l.val <= r.val) {
cur.next = l;
cur = cur.next;
l = l.next;
} else {
cur.next = r;
cur = cur.next;
r = r.next;
}
}
if (l != null) {
cur.next = l;
}
if (r != null) {
cur.next = r;
}
return tmpHead.next;
}
}