Sort a linked list in O(n log n) time using constant space complexity.
Example 1:
Input: 4->2->1->3
Output: 1->2->3->4
Example 2:
Input: -1->5->3->4->0
Output: -1->0->3->4->5
分析:
最近看到链表快排,于是用快排实现了一波,不过效果真的很差
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* sortList(ListNode* head) {
QuickSort(head, NULL);
return head;
}
void QuickSort(ListNode* left, ListNode* right)
{
if((left==NULL)||(left==right)||(left->next==right)) return;
ListNode* pivot = Partition(left, right);
if(pivot!=NULL)
{
QuickSort(left, pivot);
QuickSort(pivot->next, right);
}
}
void swap(int& a, int& b){
int temp =a;
a=b;
b=temp;
}
ListNode* Partition(ListNode*& left, ListNode*& right)
{
if(left==NULL) return NULL;
ListNode* i=left, *j=left->next;
while(j!=right)
{
if(j->val < left->val)
{
i=i->next;
swap(i->val,j->val);
}
j = j->next;
}
swap(left->val, i->val);
return i;
}
};
改用归并排序,这里的归并排序参考了stl中list的sort实现
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
static const auto __ = []() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
return nullptr;
}();
class Solution {
public:
template<class T>
void swap(T& a, T&b)
{
T temp = a;
a=b;
b=temp;
}
inline ListNode* Merge(ListNode* a, ListNode* b)
{
if(!a)
return b;
if(!b)
return a;
ListNode* head;
if(a->val < b->val)
{
head = a;
a=a->next;
}
else
{
head = b;
b = b->next;
}
ListNode* temp = head;
while((a!=NULL)&&(b!=NULL))
{
if(a->val<b->val)
{
temp->next = a;
a = a->next;
temp = temp->next;
}
else
{
temp->next = b;
b = b->next;
temp = temp->next;
}
}
if(a)
temp->next = a;
else
temp->next = b;
return head;
}
ListNode* sortList(ListNode* head) {
if((head==NULL)||(head->next==NULL))
return head;
ListNode* input;
ListNode* counter[128]={0};
int fill = 0, i;
while(1)
{
input = head;
if(!input)
break;
if(head)
head=head->next;
input->next = NULL;
i=0;
while(i<fill&&counter[i]!=0)
{
counter[i] = Merge(counter[i], input);
input = counter[i];
counter[i] = 0;
++i;
}
counter[i] = input;
input = 0;
if(i==fill)
++fill;
}
for(int i=1;i<fill;++i)
counter[i] = Merge(counter[i],counter[i-1]);
return counter[fill-1];
}
};
本文探讨了使用快速排序和归并排序两种方法对链表进行排序的实现细节。通过具体示例展示了如何在O(n log n)时间内利用常数空间复杂度完成排序过程,对比了两种算法的性能,并给出了具体的代码实现。
798

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



