我正在对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;
}
}
请告诉我如何纠正这一点,并提前感谢。
答案 0 :(得分:2)
我可以在这里看到两个可达性问题。首先是简单的:
{
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;
的位置。它是INSIDE循环。
那么,如果headA != NULL && headB != NULL
评估为假,会发生什么?在这种情况下,跳过末尾带有return 1;
的循环体......然后到达方法的末尾。
因此编译错误。
我怀疑"修复"是将return
移动到循环之后,但我没有尝试理解代码的逻辑,因此可能是错误的"修复"。
答案 1 :(得分:0)
此代码执行后会发生什么?
if(headA->data==headB->data)
{
headA=headA->next;
headB=headB->next;
}
...如果headA->next == NULL
或headB->next == NULL
?