2017-02-22 34 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.