这是我尝试实现二进制搜索链表但是在我通过递归(我讨厌递归这么多)函数“插入”输入所有信息但是当我完成并且我使用搜索功能时它总是说它无法找到价值。
我对这一切都很陌生,只是非常讨厌递归。我找不到能够正确解释它的书或教程,所以如果你有一个也有帮助的建议。
#include <iostream>
using namespace std;
struct node{
int pos;
node *left;
node *right;
};
node *list = NULL;
void invalidInput();
node *insert(node *tree, int key)
{
if(tree == NULL)
{
node *aNode = new node;
aNode->pos = key;
aNode->left = NULL;
aNode->right = NULL;
return aNode;
}
if(key < tree->pos)
{
tree->left = insert(tree->left, key);
}else
{
tree->right = insert(tree->right, key);
}
return tree;
}
node *search(node *tree, int key)
{
if(tree == NULL)
{
return NULL;
}else if(key == tree->pos)
{
return tree;
}else if(key < tree->pos)
{
return search(tree->left, key);
}else
{
return search(tree->right, key);
}
}
int main()
{
int foo, key, again;
node *tree = NULL;
cout << "What operation would you like to preform?\n1 = Insert\n2 = Search\n3 = Remove\n4 = Destroy\n";
cin >> foo;
switch(foo)
{
case 1:
cout << "Please enter a value that is not '0': \n";
cin >> key;
if(key != 0)
tree = insert(tree, key);
else
invalidInput();
while(true)
{
cout << "Please enter the next value or '0' to quit: \n";
cin >> key;
if(key != 0)
tree = insert(tree, key);
else
main();
}
break;
case 2:
do{
cout << "What value are you searching for? \n";
cin >> key;
node *searched = search(tree, key);
if(searched != NULL)
cout << searched << " was found at location: " << &searched;
else
cout << "The value you searched for was not located\n";
cout << "Would you like to search again?\n1 = Yes\n2 = No\n";
cin >> again;
}while(again == 1);
if(again != 2)
invalidInput();
else
main();
break;
}
}
void invalidInput()
{
cerr << "Sorry that was invalid. Returning you to the main menu\n";
main();
}
答案 0 :(得分:0)
您的问题是插入节点时的while
循环:
while(true)
{
cout << "Please enter the next value or '0' to quit: \n";
cin >> key;
if(key != 0)
tree = insert(tree, key);
else
main();
}
当用户想要停止插入节点时,else
子句将调用main
。但是main
做了什么?
node *tree = NULL;
当您致电main
时,您基本上是&#34;重新启动&#34;你的计划。因此,当您尝试搜索时,您正在搜索空树。
一般情况下,自己调用main
是一个非常糟糕的想法,也是设计非常糟糕的迹象。 In fact, according to the C++ standard, you should never do this.这是未定义的行为,并不保证在所有编译器中都能正常工作。
将while
循环的条件更改为while (key != 0)
并将switch
包含在另一个无限while
循环中,以便用户可以继续选择选项。