C adding node to head of linked list

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

    In C, if you want a function to be able to change a value it received in its arguments, you need to pass the address of that value. So, to change the value of the list pointer, you need to pass the address of the list pointer. Your addFirst() function should look like this :

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

    And when calling that function, you call it like this :

    addFirst(&list, value);
    

    Now, if you want to keep the function's signature, a possibility is to change the way you consider the head node. If you state that your head node is purpose is only to hold a pointer to the first value, but does not contain a value by itself, you can do something like this :

    struct node *head;
    
    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->next;
         list->next = new_node;
    }
    
    addFirst(head, 45);
    

    Now, you only have all your functions that work on the list to be change so they work the same, to consider that 'head' is only pointing to the real first node of the list but is not a member of the list itself. The 'real' head is, for all practical purpose, head->next.

提交回复
热议问题