首页 > 解决方案 > 结构指针如何区分相同指针的使用?

问题描述

这是来自极客的极客示例。最后一个例子是 root->left->left = new Node(4);我想知道左节点如何保留其旧值,并能够使用相同的结构变量连接到新值。每次调用“新节点()”时都会创建另一个内存块还是什么?我很困惑。

using namespace std;

struct Node {
    int data;
    struct Node* left;
    struct Node* right;

    // val is the key or the value that
    // has to be added to the data part
    Node(int val)
    {
        data = val;

        // Left and right child for node
        // will be initialized to null
        left = NULL;
        right = NULL;
    }
};

int main()
{

    /*create root*/
    struct Node* root = new Node(1);
    /* following is the tree after above statement

            1
            / \
        NULL NULL
    */

    root->left = new Node(2);
    root->right = new Node(3);
    /* 2 and 3 become left and right children of 1
                    1
                / \
                2    3
            / \  / \
            NULL NULL NULL NULL
    */

    root->left->left = new Node(4);
    /* 4 becomes left child of 2
            1
            /    \
        2    3
        / \  / \
        4 NULL NULL NULL
        / \
    NULL NULL
    */

    return 0;
}

标签: c++data-structuresbinary-tree

解决方案


root->left = new Node(2);并且root->left->left = new Node(4);都在内存中创建新的 Node 对象,所以你有问题

每次调用“新节点()”时都会创建另一个内存块还是什么?

有点准确。

最初,root 是一个 Node 对象,其数据值为 1,左值为 NULL。它的左指针指向任何东西。该语句root->left = new Node(2);将根左指针设置为新节点的地址。这个新节点的数据值为 2,左值为 NULL。想象一下这个新节点有一个名字,它的名字是 A。表达式root->left->left从左到右计算root->left,节点 A 也是,因此表达式变为A->leftA->left当前为 NULL。执行完root->left->left = new Node(4);A 的左指针现在指向一个数据值为 4 的新节点。


推荐阅读