控件到达非无效函数的末尾

Control reaches at the end of non-void function

本文关键字:函数 无效 控件      更新时间:2023-10-16

我正在做一个关于Hackerrank的问题,但每当我编译代码时,它都会显示控制到达非void函数的末尾。以下是我的源代码:

   /*
Compare two linked lists A and B
Return 1 if they are identical and 0 if they are not. 
Node is defined as 
struct Node
{
 int data;
 struct Node *next;
}
*/
int CompareLists(Node *headA, Node* headB)
{
if(headA==NULL&&headB==NULL)
 {
   return 1;
 }
 else if( headA!=NULL&&headB!=NULL)
 {
   while(headA!=NULL&&headB!=NULL)
    {
       if(headA->data==headB->data)
           {
           headA=headA->next;
           headB=headB->next;
             }
       else
           {
           return 0;
           exit (0);
       }
       return 1;
   }
}
else
    {
    return 0;
}
}

请告诉我如何纠正这一点,并提前表示感谢。

我可以在这里看到两个可达性问题。首先是简单的一个:

  {
      return 0;
      exit (0);
  }

无法访问exit调用。(那条线几乎肯定是个错误。我想不出有什么好的理由在那里打exit。(

下一个更复杂的。。。这就是编译错误的根本原因:

while(headA!=NULL&&headB!=NULL)
    {
       if(headA->data==headB->data)
           {
           headA=headA->next;
           headB=headB->next;
             }
       else
           {
           return 0;
           exit (0);
       }
       return 1;
   }

看看return 1;在哪里。它在循环内部。

那么,如果headA != NULL && headB != NULL的计算结果为false,会发生什么呢?在这种情况下,将跳过末尾为return 1;的循环体。。。然后你就到了方法的终点。

因此出现了编译错误。

我怀疑"修复"是将return移到循环之后,但我没有试图理解代码的逻辑,所以这可能是错误的"修复"。

执行此代码后会发生什么?

if(headA->data==headB->data)
{
     headA=headA->next;
     headB=headB->next;
}

如果是headA->next == NULL还是headB->next == NULL