C++ I';我试图用c++;但该程序只需要2个输入并停止
注意//,程序停止接收输入,这是主要问题C++ I';我试图用c++;但该程序只需要2个输入并停止,c++,search,tree,binary,C++,Search,Tree,Binary,注意//,程序停止接收输入,这是主要问题 root->cand=data 以下是完整的代码: #include <bits/stdc++.h> using namespace std; struct node { int cand; node *left; node *right; }; class candies { node *root; public: candies(); int add(int); int che
root->cand=data代码>
以下是完整的代码:
#include <bits/stdc++.h>
using namespace std;
struct node
{
int cand;
node *left;
node *right;
};
class candies
{
node *root;
public:
candies();
int add(int);
int check();
};
candies::candies()
{
root = NULL;
}
int candies::add(int data)
{
if (root == NULL)
{
root->cand = data; //code stops here
root->left = NULL;
root->right = NULL;
}
else
{
node *temp = root;
while (temp != NULL)
{
if (data < temp->cand)
{
temp = temp->left;
}
else
{
temp = temp->right;
}
}
temp = new node;
temp->cand = data;
temp->left = temp->right = NULL;
}
return 1;
}
int candies::check()
{
node *temp;
temp = root;
int data;
cin >> data;
while (temp != NULL)
{
if (temp->cand == data)
{
cout << "YES\n";
return 1;
}
else if (data < temp->cand)
temp = temp->left;
else if (data > temp->cand)
temp = temp->right;
}
cout << "NO\n";
return 0;
}
int main()
{
candies c;
int n;
cin >> n;
while (n--)
{
int data;
cin >> data;
c.add(data);
}
c.check();
}
#包括
使用名称空间std;
结构节点
{
int-cand;
节点*左;
节点*右;
};
班级糖果
{
节点*根;
公众:
糖果();
int-add(int);
int检查();
};
糖果
{
root=NULL;
}
int candies::添加(int数据)
{
if(root==NULL)
{
root->cand=data;//代码在此停止
根->左=空;
root->right=NULL;
}
其他的
{
节点*temp=root;
while(temp!=NULL)
{
如果(数据cand)
{
温度=温度->左侧;
}
其他的
{
温度=温度->右侧;
}
}
temp=新节点;
温度->坎德=数据;
临时->左=临时->右=空;
}
返回1;
}
int candies::check()
{
节点*温度;
温度=根;
int数据;
cin>>数据;
while(temp!=NULL)
{
如果(温度->坎德==数据)
{
库特(加拿大)
温度=温度->左侧;
否则如果(数据>温度->坎德)
温度=温度->右侧;
}
cout>n;
而(n--)
{
int数据;
cin>>数据;
c、 添加(数据);
}
c、 检查();
}
您首先要检查root是否为NULL。如果为NULL,则是在更改其数据。这一点都不好,会导致崩溃
if (root == NULL)
{
root->cand = data; //code stops here
如果root为NULL,则必须首先创建根节点
if ( root == nullptr ) {
root = new node;
root->cand = data;
成员函数add
无效,而且具有未定义的行为
在这个if语句中
if (root == NULL)
{
root->cand = data; //code stops here
root->left = NULL;
root->right = NULL;
}
else
{
node *temp = root;
while (temp != NULL)
{
if (data < temp->cand)
{
temp = temp->left;
}
else
{
temp = temp->right;
}
}
temp = new node;
temp->cand = data;
temp->left = temp->right = NULL;
}
使用空指针访问内存
在这个else语句中
if (root == NULL)
{
root->cand = data; //code stops here
root->left = NULL;
root->right = NULL;
}
else
{
node *temp = root;
while (temp != NULL)
{
if (data < temp->cand)
{
temp = temp->left;
}
else
{
temp = temp->right;
}
}
temp = new node;
temp->cand = data;
temp->left = temp->right = NULL;
}
如果(root==NULL){root->cand=data;
您确保它是一个空指针,然后仍然尝试访问它?请阅读。@hacxter现在在您选择“最佳”答案后,请重新阅读我的答案。:)谢谢!这看起来比我的好。@hacxter您选择的最佳答案是一个不完整的答案。