pointer of a pointer in linked list append

后端 未结 7 1823
Happy的楠姐
Happy的楠姐 2020-11-30 09:49

I normally program in python. To increase performance of my simulations, I am learning C. I have a problem to understand the use of a pointer of a pointer when implementing

7条回答
  •  自闭症患者
    2020-11-30 09:53

    You don't need the if/else; in both cases you link the new node to a pointer that was NULL before the operation. This could be the root node, or the ->next node of the last node in the chain. Both are pointers to struct node, and you need a pointer to these pointers in order to assign to them.

    void append( struct node **q, int num){
    
        while (*q){ q = &(*q)->link; }
    
        *q = malloc(sizeof **q);
        (*q)->data = num;
        (*q)->link = NULL;
    
    }
    

    Why would anyone do this? Basically because it is shorter, it uses only one loop and no additional conditions, uses no additional variables, and it can be proven to be correct. There should of course a test be added for the result of malloc, which would need an addtional condition.

提交回复
热议问题