使用并归排序。。。
时间复杂度
O(nlogn)
O
(
n
l
o
g
n
)
,空间复杂度
O(1)
O
(
1
)
。
如果是双向链表应该也能用快排。
class Solution {
public:
ListNode* sortList(ListNode* head) {
ListNode* end;
int n = getListLength(head, end);
if(n<2) return head;
ListNode* mid = getMid(head, n);
return sort(head, mid, end, n);
}
Solution() : fake_head(new ListNode(0)){}
~Solution() { delete fake_head; }
private:
ListNode* fake_head;
int getListLength(ListNode* head, ListNode* &end)
{
int n = 0;
while(head != nullptr)
{
++n;
end = head;
head=head->next;
}
return n;
}
ListNode* getMid(ListNode* mid, int n)
{
n>>=1;
for(int i=1; i<n; ++i)
mid = mid->next;
return mid;
}
ListNode* sort(ListNode* begin, ListNode* mid, ListNode* end, int n)
{
if(begin == end)
{
begin->next = nullptr;
return begin;
}
ListNode* l2start = mid->next;
ListNode* l1 = sort(begin, getMid(begin, n/2), mid, n/2);
ListNode* l2 = sort(l2start, getMid(l2start, n-n/2), end, n-n/2);
ListNode* now = fake_head;
while(l1&&l2)
{
if(l1->val<l2->val)
{
now->next = l1;
l1=l1->next;
}
else
{
now->next = l2;
l2=l2->next;
}
now=now->next;
}
if(l1 == nullptr) now->next = l2;
if(l2 == nullptr) now->next = l1;
now = fake_head->next;
return now;
}
};