简体   繁体   中英

My insert code doesn't work correctly in c

I insert nodes a Binary Search Tree. But it doesn't work correctly. This is my code :

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);            
    }   
}

PS : struct node has data , left, right . And in this insert data and x don't be the same. x is get from user and data is get from a folder and insert in different function.

let's say tree is NULL . we sometime forget that a pointer is a number. the only extra is that this number is the offset of some byte in the memory, that's all.

so taking into account that null (in C) is (void*)0 , this code:

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

can be written like this:

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

do you realize you try to assign a value to 0 ? what do we need to do in order to assign a value to a pointer, but not to the variable it points at? in other words, how should a function pass a pointer in order to change it ? (hint: as pointer to pointer)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM