以下代码在c ++中插入二进制搜索树有什么问题?
#include<iostream>
using namespace std;
struct node{
int value=0;
node *left=NULL,*right=NULL;
}*root=NULL;
Insert(int value,node *root);
InsertNode(int value,node *root);
int main()
{
Insert(5,root);
Insert(7,root);
Insert(3,root);
return 0;
}
Insert(int value,node *root)
{
if(root==NULL){
root=new node; root->value=value;cout<<endl<<value<<"inserted"<<endl;
}
else
{InsetNode(value,root);}
}
InsertNode(int value,node *root)
{
if(value<root->value){
root->left=new node;
Insert(value,root->left);
}
else{
root->right=new node;
Insert(value,root->right);
}
}
在ubuntu
中使用g ++编译时会产生以下错误9:29: error: expected constructor, destructor, or type conversion before ‘;’ token
Insert(int value,node *root);
^
10:33: error: expected constructor, destructor, or type conversion before ‘;’ token
InsertNode(int value,node *root);
^
In function ‘int main()’:
14:14: error: ‘Insert’ was not declared in this scope
Insert(5,root);
^
At global scope:
error: ISO C++ forbids declaration of ‘Insert’ with no type [-fpermissive]
Insert(int value,node *root)
^
In function ‘int Insert(int, node*)’:
error: ‘InsetNode’ was not declared in this scope
{InsetNode(value,root);}
^
At global scope:
29:32: error: ISO C++ forbids declaration of ‘InsertNode’ with no type [-fpermissive]
InsertNode(int value,node *root)
另外,我需要帮助来理解错误。
答案 0 :(得分:1)
在C ++中,返回类型的函数是必需的,不能省略:
void Insert(int value,node *root);
void InsertNode(int value,node *root);
功能定义相同。那是关于错误的。
现在为节目风格:
root
和同名的本地参数。 nullptr
代替NULL
using namespace std;
也不能让您的计划更好。 node
应该有正确定义的ctor,dtor和其他方法来提供适当的内存管理。 我错过了什么吗?
答案 1 :(得分:-1)
正如Slava所说,函数声明(和定义)缺少任何返回类型。在你的情况下,第9行应该成为:
void Insert(int value,node *root);
此外,node
不是struct node
类型。
您应该使用typedef struct foo{ ... } node;