c_cpp 使用常量空间复杂度在O(n log n)时间内对链表进行排序。
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 使用常量空间复杂度在O(n log n)时间内对链表进行排序。相关的知识,希望对你有一定的参考价值。
ListNode *mergeSort(ListNode *head) {
if(!head || !head->next) return head;
// get middle node
// not right if write: *fast = head. Otherwise, {2,1} will not be sorted.
ListNode *slow = head, *fast = head->next;
while(fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
ListNode *left = head, *right = slow->next;
slow->next = NULL;
left = mergeSort(left);
right = mergeSort(right);
return merge(left, right);
}
ListNode *merge(ListNode *L, ListNode *R) {
if(!L) return R;
if(!R) 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;
}
以上是关于c_cpp 使用常量空间复杂度在O(n log n)时间内对链表进行排序。的主要内容,如果未能解决你的问题,请参考以下文章