链表排序
在 O(n log n) 时间复杂度和常数级的空间复杂度下给链表排序。
样例
给出 1->3->2->null
,给它排序变成 1->2->3->null
.
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @param head:
* The head of linked list.
* @return: You should return the head of the sorted linked list, using
* constant space complexity.
*/
public ListNode sortList(ListNode head) {
// write your code here
if (head == null || head.next == null) {
return head;
}
ListNode mid = findMiddenNode(head);
ListNode right = mid.next;
mid.next = null;
ListNode sortLeft = sortList(head);
ListNode sortRight = sortList(right);
return mergeSort(sortLeft, sortRight);
}
public static ListNode findMiddenNode(ListNode head) {
ListNode slow = head;
ListNode fast = head.next;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
public ListNode mergeSort(ListNode left, ListNode right) {
ListNode head = new ListNode(-1);
ListNode res = head;
while (left != null && right != null) {
if (left.val > right.val) {
res.next = right;
right = right.next;
res = res.next;
} else {
res.next = left;
left = left.next;
res = res.next;
}
}
if (left != null) {
res.next = left;
}
if (right != null) {
res.next = right;
}
return head.next;
}
}