Merge two sorted link lists

筅森魡賤 提交于 2019-12-01 14:36:50

Your while loop condition is not quite right.

while(ptr1->next!=NULL || ptr2->next!=NULL)

is fine, but only when both lists are the same length!. When the lists are of different lengths, either ptr1->next or ptr2->next will be NULL, and you'll get a segmentation fault. Changing to to && is not the correct thing to do, because you'll lose the end of one of your lists!

Use this:

while((ptr1 != NULL && ptr2 != NULL) && (ptr1->next!=NULL || ptr2->next!=NULL))

Now, inside your loop you have tests like this:

if(ptr1->next->info < ptr2->info)

replace this with

if(ptr1 != NULL && ptr1->next->info < ptr2->info)

so that unequal length lists don't terminate early and don't segfault inside.

Next, inside your insert operations, you do things like

ptr1=temp;
ptr1=ptr1->next

and

ptr2=temp;
ptr2=ptr2->next;

This is bad, because temp is undefined as you never write any valid data to it! The bug here is that your assignments are the wrong way round. You should have done temp=ptr1 and temp=ptr2 respectively.

Finally, your cleanup operation to fix up equal length input lists needs to account for the fact that unequal length input lists can result in either ptr1 or ptr2 being NULL:

if(ptr1 != NULL && ptr1->next==NULL)
    ptr1->next=ptr2;
else if (ptr2 != NULL)
    ptr2->next=ptr1;

And all seems to be well. I've tested the resulting code on 1 3 5,2 4 6 and 1 3,2 and 1 4,2 3 and 1 3,2 3 and all work as I'd expect them to.

Did not check it all but lets start here :

 while(ptr1->next!=NULL || ptr2->next!=NULL)

It should be && and not || since you do not want to continue comparing when the next entry in one of the lists is null (you do use its contents in one of the ifs in the while loop)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!