【问题标题】:C++: Using recursion to find an int in a List - When to returnC++:使用递归在 List 中查找 int - 何时返回
【发布时间】:2016-09-10 03:10:56
【问题描述】:

我试图递归地遍历 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 来毁灭自己?如果头文件中已经有return false,我认为我不需要这样做。我应该删除那条线吗?有更好的方法吗?

【问题讨论】:

    标签: c++ recursion linked-list


    【解决方案1】:

    if (n == NULL) return false 很好,因为它只会在您到达列表末尾时发生并且您应该返回 false。

    我看到的第一个问题是findNode(n->next, d); 应该是return 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);
    }
    

    【讨论】:

    • 这是有道理的。我讨厌头文件,但它是导师给我的,我们不允许更改它(如果你问我,AWFUL 编码标准......)。我根本不会在头文件中这样做,但我猜你会得到你得到的。
    【解决方案2】:

    您需要进行空值检查,因为这是您确定列表结尾的方式。我猜您是在尝试将此作为练习,否则显然您根本不需要递归。

    【讨论】:

    • 是的,我通常不会使用递归,因为它非常昂贵。这是我的一门课。
    猜你喜欢
    • 1970-01-01
    • 2021-03-08
    • 1970-01-01
    • 1970-01-01
    • 2020-10-26
    • 2012-09-21
    • 2016-09-07
    • 1970-01-01
    相关资源
    最近更新 更多