Bool方法返回错误的值

时间:2015-11-01 02:25:33

标签: c++ boolean return-value boolean-logic boolean-expression

我为链表散列表创建了一个bool contains(string)方法,用于检查值是否在散列中。我使用辅助函数来递归,但当辅助函数返回false时,bool contains(string)仍然返回true。我通过调试器运行它,我可以清楚地看到它返回false,我不知道为什么。

以下是要搜索的当前节点:

"laccoliths"->"morbiferous"->"oculi"->"unscabbarded"

我正在搜索的值是"typung"

以下是代码:

bool contains_h(string x, node * p) //helper method
{
    if (p == NULL)
        return false;
    else if (x == p->data)
        return true;
    else
        contains_h(x, p->next);
}

bool contains(string word) { return contains_h(word, head); }

1 个答案:

答案 0 :(得分:7)

很简单的一个。你忘记了回归'在最后声明中:

bool contains_h(string x, node * p) //helper method
{
    if (p == NULL)
        return false;
    else if (x == p->data)
        return true;
    else
        return contains_h(x, p->next);
}

<小时/> 出于好奇,我将你的代码重写为单行代码,看看它会是什么样子:

bool contains_h(string x, node * p) //helper method
{
    return ((p!=NULL) && (x == p->data || contains_h(x, p->next)));
}

就个人而言,我更愿意阅读你的六行。但是,其他人可能不同意,特别是因为它可以避免遗漏的退货声明问题。

相关问题