Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/130.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;:使用递归在列表中查找int-何时返回_C++_Recursion_Linked List - Fatal编程技术网

C++ C++;:使用递归在列表中查找int-何时返回

C++ C++;:使用递归在列表中查找int-何时返回,c++,recursion,linked-list,C++,Recursion,Linked List,我试图递归地遍历List类中的每个节点,以查找列表中的一个节点中是否存在某个整数 这是我的头文件: class List { public: bool find(int d) const { return false; } private: Node *head; bool findNode(const Node*, int) const; }; 以下是两个函数的代码: bool List::find(int d) const { return findNod

我试图递归地遍历List类中的每个节点,以查找列表中的一个节点中是否存在某个整数

这是我的头文件:

class List
{
public:
    bool find(int d) const { return false; }
private:
    Node *head;

    bool findNode(const Node*, int) const;
};
以下是两个函数的代码:

bool List::find(int d) const
{
    return findNode(head, d);
}

bool List::findNode(const Node* n, int d) const
{
    if (n == NULL)
        return false;
    else if (n->data == d)
        return true;
    else
        findNode(n->next, d);
}
现在我的问题是:我是不是在
findNode
函数中添加了
if(n==NULL)
语句,让它总是返回false,从而让自己完蛋了?如果头文件中已经有
returnfalse
,我认为我不需要这样做。我应该删除那一行吗?还有更好的方法吗?

如果(n==NULL)返回false,那么
是好的,因为它只会在到达列表末尾时发生,并且应该返回false

我看到的第一个问题是行
findNode(n->next,d)
应该是
返回findNode(n->next,d)

第二,您需要从头文件中删除
find()
的函数体。不能两次定义函数体

因此,完整的代码是:

class List
{
public:
    bool find(int d) const;
private:
    Node *head;
    bool findNode(const Node*, int) const;
};

bool List::find(int d) const
{
    return findNode(head, d);
}

bool List::findNode(const Node* n, int d) const
{
    if (n == NULL)
        return false;
    else if (n->data == d)
        return true;
    else
        return findNode(n->next, d);
}

您需要空检查,因为这是确定列表结尾的方式。我想你是在练习,否则显然你根本不需要递归。

是的,我通常不会使用递归,因为它非常昂贵。这是给我的一个班级的,这很有道理。我讨厌头文件,但它是教练给我的,我们不允许更改它(如果你问我,糟糕的编码标准…)。我根本不会在头文件中这样做,但我想你会得到你得到的。