簡體   English   中英

函數 my_find_node 返回第一個節點出現的地址

[英]Function my_find_node that returns the address of the first node occurence

我需要幫助根據這些說明編寫函數:

編寫一個名為 my_find_node 的函數,該函數返回第一個節點出現的地址,其中包含與引用數據相等的數據。 如果沒有找到這樣的節點,則應返回 NULL。

它必須按如下方式進行原型設計:

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

目前,我的代碼由於某種原因無法編譯。

我制作了一個名為 my_list.h 的頭文件,其中包含:

    #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

這是我的函數的聲明:

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

如果有人可以幫助我使其工作或給我任何線索,那就太好了! 謝謝

您的代碼試圖匹配列表中的第 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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM