Bst-为什么我的Bst在将节点*追逐到节点*&后起作用?
Bst- Why did my Bst worked after chaning node* to node*&?
我实现了BST,我的实现看起来像这个
void insert(node*&r,int key){ // 1 ) node* r 2) node*&r
if(r==NULL){
r=new node(key);
return;
}
c++;
if(r->key > key){
insert(r->right,key);
}
else if(r->key <key){
insert(r->left,key);
}
}
int main()
{
int n;
cin>>n;
node *root=NULL;
for(int i=0;i<n;i++){
int x;
cin>>x;
insert(root,x);
}
return 0;
}
我之前很清楚为什么节点*&不是节点*。但我今天有心理障碍。我感到困惑的是,如果我们使用节点*&则我们将永久编辑作为BST标识的根,因此我们将释放BST。另一方面,我很困惑为什么它在使用节点*时不起作用。有人能详细解释一下吗。哪一个,为什么?
它现在可以工作,因为您通过引用传递指针,因此传递指针的函数可以修改它。否则,您通过值传递指针,在函数的出口处,作为参数传递的指针不会被修改。
看看这里发生了什么:
node *root=NULL; // so initially root is nullptr
然后,在for
循环中,您有
insert(root,x); // better take it by reference, otherwise root is not modified
在插入的出口处,只有通过引用传递时,才会修改root
,否则,如果通过值传递,则保持NULL
。请记住,指针的行为与任何其他变量一样,在C++中,默认情况下是按值传递的。
相关文章:
- 我的神经网络不起作用 [XOR 问题]
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- C++为什么尽管我调用了void函数,它却不起作用
- 为什么在保护模式下继承升级不起作用
- 循环在计数器中不起作用
- 在其他文件中创建类时在 c++ 项目中不起作用
- Visual studio代码重构似乎不起作用(例如,重命名符号-f2)
- 语言分析的二叉树实现 - 子节点:不起作用
- C++ Eclipse:二叉搜索树节点>数据=变量似乎不起作用
- 链接列表中的所有节点都相同,似乎插入不起作用
- 在C++中实现二叉搜索树,搜索不起作用.尝试打印节点的元素会导致输出崩溃
- 我试图键入一个函数来在单链表的末尾添加一个节点,但不起作用
- 在声明节点创建链接列表时,为什么静态内存分配不起作用
- 正在处理约瑟夫斯问题,节点函数不起作用
- 删除链表节点,C++函数不起作用
- 如何获取链表中的所有"next"节点?构建调用字符串不起作用
- 为什么这个从链表中删除节点的代码不起作用?
- 为什么我的删除节点功能不起作用?
- 删除链表中的节点不起作用?