我正在嘗試進行 BST 插入;
struct Node
{
Node* left;
Node* right;
int data;
Node(int d)
:left(nullptr), right(nullptr), data(d)
{
}
};
void Insertion(Node* head, int value)
{
if (!head)
{
head = new Node(value);
return;
}
if (head->data > value)
Insertion(head->left, value);
else
Insertion(head->right, value);
}
void printTree(Node* root)
{
if (!root)
{
return;
}
cout << root->data << " "; //20 15 10 18 30 35 34 38
printTree(root->left);
printTree(root->right);
}
int main()
{
Node *root = new Node(20);
Insertion(root, 15);
Insertion(root, 30);
Insertion(root, 10);
Insertion(root, 18);
Insertion(root, 35);
Insertion(root, 34);
Insertion(root, 38);
printTree(root);
}
我的Insertion方法無法正確插入。但是如果我像下面這樣使用它;
Node* Insertion(Node* head, int value)
{
if (!head)
{
return (new Node(value));
}
if (head->data > value)
head->left = Insertion(head->left, value);
else
head->right = Insertion(head->right, value);
return head;
}
我不確定是否Node* head是我發送的內容的副本,如果是,是否可以在不使用 Node 回傳型別但head通過參考傳遞的情況下創建相同的函式?
uj5u.com熱心網友回復:
您可以使用注釋中提到的指標參考,也可以使用指向指標的指標,如下所示:
void Insertion(Node** head, int value)
{
if (!(*head))
{
*head = new Node(value);
return;
}
if ((*head)->data > value)
Insertion(&(*head)->left, value);
else
Insertion(&(*head)->right, value);
}
并像這樣呼叫函式:
Node *root = new Node(20);
Insertion(&root, 15);
在您的代碼中,您只是將地址復制到函式引數(指標變數)。在函式內部,您正在為其分配另一個地址。但在這種情況下,這不是你想要的。您需要更改您傳遞的地址的內容。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/409914.html
標籤:
上一篇:將變數內容匯出到檔案
下一篇:訪問欄位導致取消參考C中的空指標
