2个链表合并的一些疑惑

来源:百度知道 编辑:UC知道 时间:2024/09/18 05:36:41
struct student *hebing(struct student *ahead,struct student *bhead)
{
struct student *a1,*a2,*b1,*b2;
a1=a2=ahead;
b1=b2=bhead;
while((a1->next!=NULL)||(a1==NULL&&b1!=NULL))
{
while((b1->num>a1->num)&&(a1->next!=NULL))
{a2=a1;a1=a1->next;}
if(a1->num>=b1->num)
{
if(ahead==a1)
ahead=b1;
else a2->next=b2;
b1=b1->next;
b2->next=a1;
a2=b2;
b2=b1;
}
}
if((b1!=NULL)&&(b1->num>a1->num)&&(a1->next==NULL))
a1->next=b1;
return(ahead);
}
以上是链表合并的函数 就是有一个地方不明白
while((a1->next!=NULL)||(a1==NULL&&b1!=NULL))当a链中 ahead=NULL的时候(a1==NULL&&b1!=NULL)满足运行条件 但是我觉得他是死循环啊 因为b1永远不会移动啊 为什么能运行正常呢 不理解
那是在if(a1->num>=b1->num)条件成立下才运行的 但是这个条件永远不可能成立a1->num==0 b1->num永远大于0

为了真正解决你的疑问,像下面这样:
hebing(NULL, NULL);
看程序飞不飞(崩溃)

为了解决此程序的问题,应该在函数的第一句写上:

if(ahead == NULL)
{printf("error!\n");return NULL;}
这才是具有工业强度的代码

原来的代码是学生用的
所以很高兴看到楼主能达到实用性思考的水准

外循环倒数第四句 b1=b1->next;
怎么能说b1永远不会移动呢