我正在尝试返回第一个包含值项的节点,如果没有找到则返回 NULL。我写了 2 个逻辑,在我看来它们是相同的。但是为什么我在其中一个中得到错误的输出。
//THIS IS GIVING ME THE CORRECT OUTPUT
struct nodeStruct* List_findNode(struct nodeStruct *head, int item){
struct nodeStruct *temp_node=head;
while (temp_node!=NULL)
{
if (temp_node->item == item)
{
return temp_node;
}
temp_node=temp_node->next;
}
return NULL;
}
//BUT ACCORDING ME THIS IS THE SAME LOGIC BUT IT'S GIVING WRONG OUTPUT.
struct nodeStruct* List_findNode(struct nodeStruct *head, int item){
struct nodeStruct *temp_node=head;
while (temp_node!=NULL)
{
if (temp_node->item != item)
{
temp_node=temp_node->next;
}
return temp_node;
}
return NULL;
}
最佳答案
在后一种情况下,您需要继续,否则您的函数将始终返回
while (temp_node!=NULL)
{
if (temp_node->item != item)
{
temp_node=temp_node->next;
continue; // here
}
return temp_node;
}
也就是说你也可以使用 for 循环:
struct nodeStruct* List_findNode(struct nodeStruct *head, int item) {
for (struct nodeStruct *temp_node = head;
temp_node != NULL;
temp_node = temp_node->next) {
if (temp_node->item == item) {
return temp_node;
}
}
return NULL;
}
关于c - 我正在尝试返回第一个持有值(value)项目的节点,如果没有找到则返回 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56313435/