我试图返回保存值项的第一个节点,或者如果找不到则返回NULL

时间:2019-05-26 12:18:04

标签: c gcc linked-list

我正在尝试返回包含值项的第一个节点,或者如果找不到则返回NULL。我写了两种逻辑,根据我的观点,它们是相同的。但是为什么我其中之一输出错误。

//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;
}

1 个答案:

答案 0 :(得分:2)

在以后的情况下,您需要继续,否则函数将始终返回

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;
}