仅仅为了澄清,恒定空间意味着O(1)空间,对吧? 无论如何,这是我写的代码,请告诉我它是否使用O(1)空格。
void mergeSort() {
ListNode merge = this.head;
this.head = mergeSort(merge);
}
ListNode mergeSort(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode slow = head; ListNode fast = head.next;
while(fast!=null && fast.next !=null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode left = head; ListNode right = slow.next;
slow.next = null;
left = mergeSort(left);
right = mergeSort(right);
return merge(left, right);
}
ListNode merge(ListNode L, ListNode R) {
if(L==null) return R;
if(R==null) return L;
ListNode h = null;
if(L.val <= R.val )){
h = L;
h.next = merge(L.next, R);
} else {
h = R;
h.next = merge(L, R.next);
}
return h;
}