首页 > 解决方案 > Function my_find_node that returns the address of the first node occurence

问题描述

I need help to write a function according to these instructions:

Write a function named my_find_node that returns the address of the first node occurence, which contains data equal to the reference data. If no such node is found, NULL should be returned.

It must be prototyped as follows:

linked_list_t *my_find_node(linked_list_t *list, const int data_ref);

For the moment, my code doesn't compile for some reason.

I have made a header file named my_list.h which contains:

    #ifndef __MYLIST__H__
    #define __MYLIST__H__

    typedef struct linked_list_t
    {
    int x;
    struct linked_list_t *next;
    }linked_list_t;

linked_list_t *my_find_node(linked_list_t *list, const int data_ref);

#endif

And here is the declaration of my function:

#include <stdio.h>
#include <stdlib.h>
#include "mylib.h"


linked_list_t *my_find_node(linked_list_t *list, const int data_ref)
    {
        linked_list_t *current = list;

        int count = 0;

        if(current == NULL)
            return (NULL);

    while (list != NULL)
    {
        if (count == data_ref)
            return element;

        count++;
        current = current->next;
    }
    return (NULL);
}

If someone can help me to make it work or give me any clue, would be great! Thanks

标签: clistpointersstructcompiler-errors

解决方案


您的代码试图匹配列表中的第 N 个元素,而不是匹配节点的内容/值。

另外,element没有定义。而且,您正在做while (list != NULL)但正在做current = current->next,因此,实际上,您遇到while (1)了其他问题。

它实际上有点简单,基于问题定义(即包含与参考数据相等的数据)。这是一个稍微重构的版本:

linked_list_t *
my_find_node(linked_list_t *list,const int data_ref)
{
    linked_list_t *current;

    for (current = list;  current != NULL;  current = current->next) {
        if (current->x == data_ref)
            break;
    }

    return current;
}

推荐阅读