Problem:
Sort a linked list in O(n log n) time using constant space complexity.
Example 1:
Input: 4->2->1->3 Output: 1->2->3->4Example 2:
Input: -1->5->3->4->0 Output: -1->0->3->4->5
Analysis:
本题的要求是空间复杂度为O(nlogn),对于排序算法分为两种,一种是内部排序算法,另外一种是外部排序算法。对于内部排序算法,其时间复杂度要高,但是空间复杂度一般是常数;而对于外部排序算法一般需要使用额外的存储空间,因此此题考虑使用归并排序算法。代码如下:
Code:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode sortList(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode slow = head;
ListNode fast = head;
while(fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
fast = slow.next;
slow.next = null;
return mergeNodes(sortList(head), sortList(fast));
}
private ListNode mergeNodes(ListNode left, ListNode right) {
ListNode res = new ListNode(-1);
ListNode cur = res;
while(left != null && right != null) {
if(left.val <= right.val) {
cur.next = left;
left = left.next;
} else {
cur.next = right;
right = right.next;
}
cur = cur.next;
}
if(left != null) {
cur.next = left;
} else if(right != null) {
cur.next = right;
}
return res.next;
}
}