简体   繁体   中英

Binary search tree. Pointer as reference parameter

So I am working on Binary search tree function. Why do I have to add a &sign in front of the node pointer? I thought it is already a pointer and it already points to a location. I understand that if I add a node, then I need to make sure the parent node point to the new node or the parent's node will still point to NULL. But why don't I have to do that if I pass my node pointer as 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;
}
}

Thank you

node*& x is a reference to a node* . This means that when bst::remove123 modifies x to point to a different address, the code that called bst::remove123 sees the same change in the node* variable that it passed to the method. If you declared the x parameter as node *x instead, then bst::remove123 would only be modifying a copy of the variable passed in that parameter, and those changes would be lost after the method returned. While the & is used to designate a reference, this is very different to the & operator (often used with pointers) which returns the address of the variable following it.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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