C adding node to head of linked list

前端 未结 6 1136
小蘑菇
小蘑菇 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:43

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

    This is the correct code. the problem is that the poineter struct node *list You are passing can't be changed as it is a stack variable. If you change it to struct node **list you are passing a pointer to the first node of the list. now you can change that to point to the new first node of the list.

提交回复
热议问题