gpt4 book ai didi

c - 我的插入代码在 c 中无法正常工作

转载 作者:行者123 更新时间:2023-11-30 15:27:17 26 4
gpt4 key购买 nike

我将节点插入二叉搜索树。但它无法正常工作。这是我的代码:

int adding(node * tree,double x,int y)
{
node *newN;

if(!tree)
{
newN=(node*)malloc(sizeof(node));
newN->data=x;
newN->totalval=y;
newN->right=NULL;
newN->left=NULL;
tree=newN;
return 1;
}

if(x < tree->data)
{
adding(tree->left,x,y);
}

if(x==tree->data)
{
printf("This data is already existed. Please try again");
return 0;
}

if(x> tree->data)
{
adding(tree->right,x,y);
}
}

P.S:结构节点有数据,左,右。并且在这个插入数据和x不一样。 x 是从用户获取的,数据是从文件夹获取并插入到不同的函数中。

最佳答案

假设NULL。我们有时会忘记指针是一个数字。唯一额外的是这个数字是内存中某个字节的偏移量,仅此而已。

因此考虑到 null(在 C 中)是 (void*)0,此代码:

if(!tree)
{
newN=(node*)malloc(sizeof(node));
newN->data=x;
newN->totalval=y;
newN->right=NULL;
newN->left=NULL;
tree=newN;
return 1;
}

可以这样写:

 if(!tree)
{
//...
(void*)0 = newN;
return 1;
}

您是否意识到您正在尝试为 0 赋值?为了给指针赋值,而不是给它指向的变量赋值,我们需要做什么?换句话说,函数应该如何传递指针才能更改它? (提示:作为指向指针的指针)

关于c - 我的插入代码在 c 中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27083902/

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