Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C adding node to head of linked list

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 :

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

I create a list (malloc and everything), then call this method, it adds the new node inside the method but when i get back to my main my old list remains unchanged. Using DDD debugger to check everything. How is this possible? I am not able to change the method signature so it has to be done like this.

like image 483
Onica Radu Avatar asked Nov 28 '25 06:11

Onica Radu


2 Answers

If you really need to do it this way, you have to re-cast the pointer. Something like this:

struct node *my_list = null;
addFirst((struct node *)&my_list, 123);

void addFirst(struct node *list, int value){
    struct node **real_list = (struct node **)list;
    struct node *new_node = (struct node*) malloc (sizeof (struct node));
    new_node->value = value;
    new_node->next = *real_list;
    *real_list = new_node;
}
like image 189
Johnny Mopp Avatar answered Nov 30 '25 19:11

Johnny Mopp


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);
like image 40
MOHAMED Avatar answered Nov 30 '25 19:11

MOHAMED



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!