gpt4 book ai didi

c - 为什么插入节点后需要返回 BST 中的头指针?

转载 作者:行者123 更新时间:2023-11-30 17:43:48 24 4
gpt4 key购买 nike

#include<stdio.h>
#include<stdlib.h>

typedef struct BTreeNode BTNode;
struct BTreeNode
{
int value;
struct BTreeNode *left_child,*right_child;
};

BTNode* insert(int input_value, BTNode **head_node)
{
BTNode *temp,*head;
temp = malloc(sizeof(BTNode));
temp->value = input_value;
temp->left_child = NULL;
temp->right_child = NULL;
head = *head_node;
while(1)
{
if(head == NULL)
{
head = temp;
// break;
return head;
}
if(temp->value > head->value)
{
if(head->right_child == NULL)
{
head->right_child=temp;
}
else
head = head->right_child;
}
else if(temp->value < head->value)
{
if(head->left_child == NULL)
{
head->left_child=temp;
}
else
head = head->left_child;
}
else
{
break;
}
}
return *head_node;
}

int insert_wor(int input_value, BTNode **head_node)
{
BTNode *temp,*head;
temp = malloc(sizeof(BTNode));
temp->value = input_value;
temp->left_child = NULL;
temp->right_child = NULL;
head = *head_node;
while(1)
{
if(head == NULL)
{
head = temp;
// break;
return 1;
}
if(temp->value > head->value)
{
if(head->right_child == NULL)
{
head->right_child=temp;
}
else
head = head->right_child;
}
else if(temp->value < head->value)
{
if(head->left_child == NULL)
{
head->left_child=temp;
}
else
head = head->left_child;
}
else
{
return -1;
}
}
return 1;
}

void printtree(BTNode **head_node)
{
BTNode *head;
head = *head_node;
if(head == NULL)
{
// printf("Print exit\n");
return;
}
else
{
printf("%d\n",head->value);
printtree(&(head->left_child));
printtree(&(head->right_child));
}
}

int main()
{
BTNode *root=NULL,*root_wor=NULL;
root=insert(23,&root);
root=insert(32,&root);
root=insert(230,&root);
root=insert(3,&root);
root=insert(2,&root);
root=insert(50,&root);
printtree(&root);
insert_wor(24,&root_wor);
insert_wor(42,&root_wor);
insert_wor(45,&root_wor);
insert_wor(12,&root_wor);
insert_wor(87,&root_wor);
insert_wor(123,&root_wor);
printtree(&root_wor);
}

在上面的代码中,我编写了两个不同的函数来在 BST 中插入节点。1)在一个函数中,我在插入节点后返回头指针。2)在第二个函数中,我没有返回头指针。当我尝试打印 BST 时,第一个工作正常,但我无法打印第二次 BST。我的疑问是,根据指针的概念,即使我们在成员函数中进行更改,它也应该反射(reflect)在主函数中,但在这种情况下(在第二种方法中,当我传递 head 并在成员函数中对其进行更改时,它们是没有反射(reflect)在主函数中)这没有发生?我想我在某些时候感到困惑。有人可以帮忙澄清一下吗?

谢谢

最佳答案

在第二个版本中,head = *head_node; 复制头指针。当您稍后更改 head 时,原始指针(由 head_node 指向)将永远不会更新。如果您始终使用 *head_node 而不是它的副本,或者在返回之前分配了 *head_node = head;,则 insert_wor() 函数也可以工作。

关于c - 为什么插入节点后需要返回 BST 中的头指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20172603/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com