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;
}
写正确函数需要注意的地方:链表的合并排序
最新推荐文章于 2024-04-01 09:00:40 发布