[英]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::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.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.