c++ - 为什么指针在 C++ 中丢弃值?
问题描述
这是一个简单的二叉搜索树(BST),我用它来说明我的问题
struct BST {
int key;
BST *left, *right;
};
这是一个将节点插入 BST的函数:
bool insert (BST *root, BST *node) {
// base case. Do the insertion
if (root == nullptr) {
root = node;
return true;
}
if (root->key < node->key)
insert(root->left, node);
else
insert(root->right, node);
}
这是我的主要内容:
int main () {
// Make a root for the BST
BST root = {10, nullptr, nullptr};
BST *root_p = &root;
// Insert node into BST
BST node = {5, nullptr, nullptr};
BST *node_p = &node;
insert(root_p, node_p);
// Should see the address of the inserted node
cout << root_p->left << endl; // it outputs 0 (nullptr). Why?
}
我正在尝试在 BST 上进行插入。我首先初始化了根,然后是一个指向根的指针,称为root_p
. BST 中的任何插入都将从root_p
. 然后我尝试在 BST 中插入一个新节点。
理想情况下,insert(root_p, node_p)
应该导致root_p
' 左指针的值node_p
(遵循 BST 约定,其中左孩子的键较小)。然而,这并没有发生,而是root_p
左指针仍然是一个空指针。为什么呢?任何帮助表示赞赏!
PS:我尝试将 insert 更改为对指针进行引用(即BST *&root
),但这会产生相同的结果。
解决方案
推荐阅读
- mongodb - 在 MongoDB 中迁移数据
- python - Imagemagick 魔杖使用深度不像命令行那样工作
- javascript - 处理来自控制台的nodeJs输入?
- javascript - 仅将简单的 php web 应用程序转换为 LAN
- angularjs - 如果进度条为 100%,AngularJS 删除“活动”类
- python - Python 3 web scraper 非常简单不工作
- python - 如何通过比较另一个数据框中的值来为数据框的列分配值
- delphi - 在delphi中自动增加轨迹栏的过程
- python - Python3:从给定时间播放音频文件
- python - 为什么 day_num 没有定义?