Sort a linked list in O(n log n) time using constant space complexity.
用mergeSort.快排的时间复杂度最差是n^2;
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *mergeList(ListNode *head1,ListNode *head2){ if(!head1)return head2; if(!head2)return head1; ListNode * res = new ListNode(-1); ListNode * tmp = res; ListNode * p = head1; ListNode * q = head2; while(p && q){ if(p->val<=q->val){ tmp->next = p; tmp = p; p = p->next; }else{ tmp->next = q; tmp = q; q = q->next; } } if(p) tmp->next = p; if(q) tmp->next = q; return res->next; } ListNode* sortList(ListNode* head) { if(!head || !head->next){ return head; } ListNode *pSlow = head; ListNode *pFast = head; while(pFast->next && pFast->next->next){ pFast = pFast->next->next; pSlow = pSlow->next; } ListNode *head2= pSlow->next; pSlow->next = NULL; ListNode *head1= head; head1 = sortList(head1); head2 = sortList(head2); return mergeList(head1,head2); } };
本文介绍了一种在O(nlogn)时间内使用常数空间复杂度对链表进行排序的方法,利用归并排序实现,避免了快速排序在最坏情况下的n^2时间复杂度。文章提供了详细的C++代码实现。
2326

被折叠的 条评论
为什么被折叠?



