2017-02-22 108 views
0

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

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; 
} 
} 

谢谢

+0

'&'不是这里的运算符地址,它是一个引用声明。你需要回头重读C++书中指针和引用的解释。参数需要作为参考的原因是,当节点被删除时,被删除节点的原始指针需要被替换,在这个递归上下文中,最简单的方法是使用一个引用。有关引用的更多信息,请参阅C++书籍。 –

+0

当你需要修改'T *'类型的指针时,你传入了一个指针类型'T *&'的引用。指针类型的引用就像对其他类型的引用一样。 – 2017-02-22 02:04:33

回答

0

node*& x是一个node*参考。这意味着当bst::remove123修改x以指向一个不同的地址时,调用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.