您的位置:首页 > 其它

写正确函数需要注意的地方:链表的合并排序

2014-03-04 12:12 211 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐