我正在尝试使用 c++ 编写二叉搜索树,但该程序仅接受 2 个输入并停止
I'm trying to code a binary search tree using c++ but the program takes only 2 inputs and stops
注意//,程序停止接受输入,这是主要问题。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 << "YESn";
return 1;
}
else if (data < temp->cand)
temp = temp->left;
else if (data > temp->cand)
temp = temp->right;
}
cout << "NOn";
return 0;
}
int main()
{
candies c;
int n;
cin >> n;
while (n--)
{
int data;
cin >> data;
c.add(data);
}
c.check();
}
成员函数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;
}
创建的节点temp
不会添加到树中。所以程序有内存泄漏。
可以按以下方式编写该函数。最好将其返回类型设为void
。否则,函数实现中的返回值 1 没有意义。
class candies
{
node *root;
public:
candies();
void add(int);
int check();
};
//...
void candies::add( int data )
{
node **current = &root;
while ( *current != nullptr )
{
if ( data < ( *current )->cand )
{
current = &( *current )->left;
}
else
{
current = &( *current )->right;
}
}
*current = new node { data, nullptr, nullptr };
}
您首先要检查根是否为 NULL。如果是,则您正在更改其数据。这根本不好,会导致崩溃。
if (root == NULL)
{
root->cand = data; //code stops here
如果根为 NULL,则必须先创建根节点。
if ( root == nullptr ) {
root = new node;
root->cand = data;
相关文章:
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 无法在windows控制台中为C++程序提供必要的输入
- 更改.cpp程序的输入文件中数据的位置会意外更改输出
- 我试图制作一个程序,要求用户输入问题和答案,但程序循环不正确
- 我的程序没有从文件中读取并输入数据
- 3-3. 编写一个程序来计算每个不同单词在其输入中出现的次数
- LLVM | codegen 用于带有命令行选项的程序输入功能
- 程序输入名称和高度并显示它。我不知道如何显示列表中最高人的姓名和身高
- 程序输入密码并解锁窗口7,8,10
- 堆栈程序输入名称并重印在C 中
- C 程序输入超过某些输入行时行不通
- C++程序 - 输入文本流
- 当程序输入主要功能时,为什么要清除此std ::向量
- 在不模拟Ctrl+V的情况下将数据粘贴到任何应用程序输入字段中.Windows c++
- c++ 将函数输出重定向到编译的程序输入,反之亦然
- 程序输入只识别单词而不识别行
- 如何与Node.js进程中的C++程序输入流进行交互
- C++命令行实用程序输入文件的位置会更改行为
- 我的程序输入无法保存到文本文件中
- 提示用户为缩写程序输入字符串