Node* mergeSort(Node* head, int length)
{
if(length==0)
return NULL;
if(length==1)
{
head->pNext=NULL;//一定要赋值为NULL,否则可能出现死循环。
return head;
}
int halflength=length/2;
Node* halfp=head;
for(int i=0;i<halflength;++i)
halfp=halfp->pNext;
Node* p1=mergeSort(head, halflength);
Node* p2=mergeSort(halfp,length-halflength);
//merge部分
Node* result=NULL;
if(p1->value>p2->value)
{
result=p2;
p2=p2->pNext;
}
else
{
result=p1;
p1=p1->pNext;
}
Node* tail=result;
while(p1!=NULL && p2!=NULL)
{
if(p1->value>p2->value)
{
tail->pNext=p2;
tail=tail->pNext;
p2=p2->pNext;
}
else
{
tail->pNext=p1;
tail=tail->pNext;
p1=p1->pNext;
}
}
tail->pNext=(p1==NULL?p2:p1);
return result;
}
Node* mergeSort(Node* head)
{
if(head==NULL || head->pNext==NULL)
return head;
int length=0;
Node* cur=head;
for(;cur!=NULL;cur=cur->pNext)
++length;
mergeSort(head,length);
}
int _tmain(int argc, _TCHAR* argv[])
{
srand(time(0));
int size=rand()%20;
Node* head=NULL;
for(int i=0;i<size;++i)
addHead(rand()%50,head);
print(head);
print(mergeSort(head));
getchar();
return 0;
}
写正确函数需要注意的地方:链表的合并排序
最新推荐文章于 2025-09-18 20:41:10 发布
本文详细介绍了C++中归并排序算法的实现过程及优化技巧,包括递归分解与合并步骤,特别关注了避免死循环的细节处理,通过实例演示了如何在不同长度的链表中进行排序操作,并最终展示了排序前后的对比结果。

5万+

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



