2014-11-22 95 views
0

我插入节点二进制搜索树。但它不能正常工作。这是我的代码:我的插入代码在c中无法正常工作

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:struct node有数据,左边,右边。而在这个插入数据和x不一样。 x从用户获取,数据从文件夹获取并插入不同的功能。

+1

'tree = newN;'没有效果。因为'树'是局部变量。 'int add(node * tree,double x,int y){' - >'int adding(node ** tree,double x,int y){'并且有一个路径不返回值。 – BLUEPIXY 2014-11-22 23:56:21

回答

1

比方说treeNULL。 我们有时会忘记指针是一个数字。唯一的额外的是这个数字是内存中某个字节的偏移量,就这些了。

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

+1

正确的答案,但不要问修辞问题 - 以防万一OP不*知道答案。 – usr2564301 2015-05-23 00:58:09