gpt4 book ai didi

c - 在C中递归搜索链表

转载 作者:太空宇宙 更新时间:2023-11-04 05:59:03 25 4
gpt4 key购买 nike

我是 C 语言的新手,我试图编写一种递归搜索链表的方法,但没有成功。如果在链表的任何节点中都找不到该名称,并且找到了 1,则该函数包含返回 0。我似乎陷入了无限循环。任何帮助将不胜感激!

#include<stdlib.h>
#include<string.h>

struct node
{
char name[1000];
struct node *next;
};

int contains(const struct node *pNode, const char *name)
{
int i;
int length = strlen(name);
int isEqual = 0;

while (pNode != NULL)
{
isEqual = 1;
for (i = 0; i < length; i++)
{
if (pNode->name[i] != name[i])
{
isEqual = 0;
}
}
}

contains(pNode->next, name);

return isEqual;
}

main()
{
struct node node1 = { "Sam", NULL };
struct node *node1Ptr = &node1;
struct node node2 = { "Anna", node1Ptr };
struct node *node2Ptr = &node2;
struct node node3 = { "Adam", node2Ptr };
struct node *node3Ptr = &node3;

int n, k;

// testing for a name that is the list
n = contains(node3Ptr, "Sam");
printf("%d\n", n);
// testing for a name that is not in the list
k = contains(node3Ptr, "Max");
printf("%d\n", k);
}

最佳答案

您的函数可以简明地写成:

#include <string.h>
...
int contains(const struct node *pNode, const char *name)
{
if(pNode == NULL)
return 0;
if(strcmp(pNode->name, name) == 0)
return 1;
return contains(pNode->next, name);
}

请注意,您的代码中对 contains() 的递归调用的值永远不会被使用,因此永远不会提供任何有用的信息。它的调用在最后无条件完成,这就解释了无限循环。

编译时启用所有(合理的)警告(GCC 和 clang 的 -Wall),它应该会告诉您很多错误信息。作为一项个人政策,如果它不是 -Wall 干净的,最好有充分的理由相信我是对的并且编译器过于热心。

您还可以简化数据结构的大部分设置,但那是以后的事了。

很高兴您根据需要用 const 进行了装饰。

关于c - 在C中递归搜索链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22046907/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com