【问题标题】:Pointers in recursion not working as expected递归中的指针未按预期工作
【发布时间】:2022-01-13 06:38:34
【问题描述】:

我正在尝试插入 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 是否是我发送的内容的副本,如果是,是否可以在不使用节点返回类型但通过引用传递head 的情况下创建相同的函数?

【问题讨论】:

  • 请记住,C++ 中的参数默认是按值传递。这意味着调用中使用的值将被复制到函数参数变量中,并且当函数返回时,对参数变量的任何修改(如对其赋值)都将丢失。请投资some decent books 并阅读references 以及如何通过引用传递参数。恰当的例子:在您分配给headInsertion 函数中。当函数返回时,该赋值丢失。
  • head 是一个值参数。当您从Insertion() 返回时,它的修改将丢失。为了防止这种情况,您必须将其类型更改为Node*&amp; head - 对节点指针的引用。另一种方法是在调用端应用Insertion() 的返回值,因为这是之后Node* head 的更新值,例如root = Insertion(root, 15);.
  • @Scheff'sCat,谢谢Node*&amp; head 我不知道指针也可以通过引用传递。
  • @Someprogrammerdude 谢谢你的链接,我会试试那里提到的一些书
  • 虽然不能代替买一本好书,这里有一个在线教程的链接,它解释了通过by valueby pointerby reference之间的区别。

标签: c++ pointers recursion reference pass-by-reference


【解决方案1】:

您可以使用注释中提到的指针引用,也可以使用指向指针的指针,如下所示:

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

在您的代码中,您只是将地址复制到函数参数(指针变量)。在函数内部,您正在为其分配另一个地址。但在这种情况下,这不是你想要的。您需要更改您传递的地址的内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-10
    • 2020-12-26
    • 1970-01-01
    • 1970-01-01
    • 2018-08-19
    • 1970-01-01
    相关资源
    最近更新 更多