【问题标题】:My insert code doesn't work correctly in c我的插入代码在 c 中无法正常工作
【发布时间】:2014-11-22 23:47:57
【问题描述】:

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

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 是从用户那里获取的,数据是从一个文件夹中获取的并插入到不同的函数中。

【问题讨论】:

  • tree=newN; 无效。因为tree 是局部变量。 int adding(node * tree,double x,int y){ --> int adding(node ** tree,double x,int y){ 并且有一个不返回值的路径。

标签: c insert tree


【解决方案1】:

假设tree 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 赋值?我们需要做什么才能给指针赋值,而不是给它指向的变量赋值?换句话说,一个函数应该如何传递一个指针来改变它? (提示:作为指针的指针)

【讨论】:

  • 正确答案,但尽量不要问反问 - 以防 OP 确实知道答案。
猜你喜欢
  • 2022-11-16
  • 2015-10-26
  • 2015-07-02
  • 1970-01-01
  • 1970-01-01
  • 2021-12-27
  • 1970-01-01
  • 1970-01-01
  • 2011-06-03
相关资源
最近更新 更多