語言:JAVA
思路:要是o(nlogn)時間內排序一個鏈表,並且要求常量空間複雜度。那麼使用歸併排序,並且將原表分成兩個表,使用原表的空間進行。
代碼:
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode sortList(ListNode head) {
if (head==null || head.next==null) {
return head;
}
ListNode rightStart = head;
ListNode curorIndex = head.next.next;
while (curorIndex!=null &&curorIndex.next!=null) {
rightStart = rightStart.next;
curorIndex = curorIndex.next.next;
}
ListNode right = sortList(rightStart.next);
rightStart.next = null;
return merge_sort(sortList(head), right);
}
public ListNode merge_sort(ListNode left, ListNode right) {
ListNode head = new ListNode(Integer.MIN_VALUE);
ListNode tail = head;
while (left!=null && right!=null) {
if (left.val > right.val) {
tail.next = right;
right = right.next;
} else {
tail.next = left;
left = left.next;
}
tail = tail.next;
}
if (left != null)
tail.next = left;
if (right != null)
tail.next = right;
return head.next;
}
}