c - 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
解决方案
您的代码试图匹配列表中的第 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;
}
推荐阅读
- python-3.x - 导入 stl 模型 PyQt3D 和 Pyinstaller
- amazon-web-services - 使用 COPY 命令从 s3 插入具有特殊字符(如 \ \n " ' )的数据到从 springboot 项目红移时出现问题
- pandas - 熊猫将多列堆叠成多列
- c++ - 字符串推回问题的向量,你们能帮我吗?
- typescript - Typescript 泛型函数,带有关于索引类型的断言
- swift - Firebase 数据库不会停止更新
- android - 在 ViewModel 环境中哪里轮询传感器数据?
- xcode - SwiftUI Xcode 11 beta 7 @Binding for collections 正在打破预览
- javascript - 为什么我的计时器不会每三天动态重置一次?
- c# - 无效的 URI:无法确定 URI 的格式