我对 code 感到困惑下面:
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
struct node* insert(struct node* node, int data)
{
/* 1. If the tree is empty, return a new,
single node */
if (node == NULL)
return(newNode(data));
else
{
/* 2. Otherwise, recur down the tree */
if (data <= node->data)
node->left = insert(node->left, data);
else
node->right = insert(node->right, data);
/* return the (unchanged) node pointer */
return node;
}
}
newNode
返回指向它已分配的结构的指针。然而,在 insert
函数的第 6 行中,newNode
的返回值没有被分配给任何东西,它只是被调用了。代码如何进一步向下能够使用新创建的节点结构?
最佳答案
如果树不是是空的,下面的代码将会运行。因此,当步骤 .2 中的代码运行时,步骤 .1 中的代码不会运行。
当递归展开时,您可以看到分配操作正在发生,例如:
node->left = insert(node->left, data);
哦,正如 ThunderWiring 所说,do not cast malloc!
关于c - 返回结构指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32550492/