C++ C++;:使用递归在列表中查找int-何时返回
我试图递归地遍历List类中的每个节点,以查找列表中的一个节点中是否存在某个整数 这是我的头文件: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
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);
}
您需要空检查,因为这是确定列表结尾的方式。我想你是在练习,否则显然你根本不需要递归。是的,我通常不会使用递归,因为它非常昂贵。这是给我的一个班级的,这很有道理。我讨厌头文件,但它是教练给我的,我们不允许更改它(如果你问我,糟糕的编码标准…)。我根本不会在头文件中这样做,但我想你会得到你得到的。