繁体   English   中英

二进制搜索树。 指针作为参考参数

[英]Binary search tree. Pointer as reference parameter

所以我正在研究二叉搜索树功能。 为什么我必须在节点指针前面添加&符号? 我认为它已经是一个指针,并且已经指向一个位置。 我了解如果添加节点,则需要确保父节点指向新节点,否则父节点仍将指向NULL。 但是,如果我将节点指针作为node *&传递,为什么不必这样做呢?

bool bst::remove123(int data, node*& x)
{
if (x == NULL)
{
    return false;
}
else if (x->getData() < data)
{
    return remove123(data, x->right);
}
else if (x->getData() > data)
{
    return remove123(data, x->left);
}
else
{
    node* old = x;
    if (x->left == NULL)
    {
        x = x->right;
    }
    else if (x->right == NULL)
    {
        x = x->left;
    }
    else
    {
        replacement(old, x->left);
    }
    delete old;
    return true;
}
}

谢谢

node*& x是对node*的引用。 这意味着,当bst::remove123x修改为指向另一个地址时,称为bst::remove123的代码会在传递给该方法的node*变量中看到相同的更改。 如果改为将x参数声明为node *x ,则bst::remove123将仅修改该参数中传递的变量的副本 ,并且这些更改将在方法返回后丢失。 虽然&用于指定引用,但这与&运算符(通常与指针一起使用)非常不同,后者返回变量后的地址。

int n = 10;
int *pn = &n; // Create a pointer to int, set it to the address of n.
int& rn = n; // Create an int reference, set it to reference the same variable as n.

*pn = 5; // Set n to 5 via a dereferenced pn. A dereferencing operator *
         // is needed to indicate that we want to change the memory that
         // pn points to, not the address that the pointer contains.

rn = 20; // Set n to 20 via the reference rn. Unlike with pointers,
         // references do not use a dereferencing operator.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM