C adding node to head of linked list

前端 未结 6 1096
小蘑菇
小蘑菇 2021-01-22 05:48

I have created a linked list struct in c

struct node{
   int value;
   struct node* next;
};

a method to add a node at the start of the list :

6条回答
  •  囚心锁ツ
    2021-01-22 06:48

    the node pointer could not be changed into the function in this way. in the function you are able to change the content of the pointer and not the address of the pointer. To do you have to pass your pointer of pointer struct node **list

    here after how to do it:

    void addFirst(struct node **list, int value){
        struct node *new_node = (struct node*) malloc (sizeof (struct node));
        new_node->value = value;
        new_node->next = *list;
        *list = new_node;
    }
    

    or you can do it in this way

    struct node * addFirst(struct node *list, int value){
        struct node *new_node = (struct node*) malloc (sizeof (struct node));
        new_node->value = value;
        new_node->next = list;
        return new_node;
    }
    

    and in your cod you can get the head after the call of this function

    head = addfirst(head,45);
    

提交回复
热议问题