description:
Sort a linked list in O(n log n) time using constant space complexity.
题目要求使用O(nlogn)的时间复杂度和确定的控件复杂度,但是一开始的时候没有注意到确定的个空间复杂度这一个词,结果使用了merge sort的排序方式。
没有通过测试,但是也可以拿出来写一写,其中的有些内容还是非常有意思的。
merge sort是一种稳定排序,使用分值的方式进行实现。
开始的时候,要有首先计算ListNode right,然后让middle.next = null,此处是为了让left的内容随着right变化,否则就可能出现内存溢出的情况。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode sortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode middle = findMiddle(head);
ListNode right = sortList(middle.next);
middle.next = null;
ListNode left = sortList(head);
ListNode value = mergeListNode(left, right);
return value;
}
private ListNode findMiddle(ListNode node) {
ListNode slow = node;
ListNode fast = node.next;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
private ListNode mergeListNode(ListNode left, ListNode right) {
ListNode dummy = new ListNode(0);
ListNode head = dummy;
while (left != null && right != null) {
if (left.val > right.val) {
head.next = right;
right = right.next;
} else {
head.next = left;
left.next = left.next;
}
head = head.next;
}
if (left != null) {
head.next = left;
} else {
head.next = right;
}
return dummy.next;
}
}