c - 我正在尝试返回第一个持有值(value)项目的节点,如果没有找到则返回 NULL

标签 c gcc linked-list

我正在尝试返回第一个包含值项的节点,如果没有找到则返回 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/

相关文章:

oop - 递归调用一个类(实现链表)

c - 尝试检查一个二维字符数组中第二个二维字符数组中的关键字

更改函数内变量的值

c++ - CMake 发现错误的 gcc 版本

c++ - G++ 编译统计

c - C中的简单链表(2): Trash result

c - 通过*指针分配后,相邻的内存块将被零填充。为什么?

c - 指针问题

无法在 malloc() 处设置断点

c - 数组性能与 LinkedList 非常相似 - 给出了什么?