0

Arrccoding to algorithm of insertion at the beginning of linked list. I try to implement this by C as below:

void insert(node *head, int value)
{
    if (head != NULL)
    {
        //Create a temp allocation n
        node *n = malloc(sizeof(node));
        // Set address of current head (first node) to n
        n->number = value;
        n->next = head;
        //Set head
        head = n;
    }
    else
    {
        printf("List is not exist\n");
    }
}

Output of linked list before insert: 1, 2, 3

Output of linked list expect after inset with value = 4: 4, 1, 2, 3

I called the function

insert(head, 4)

but it seems like nothing happen.

I did debug into the function and everything worked well. n-> name was updated with argument value and n-> next was updated with current head's pointer. Then, head was updated by new pointer n in this function. But when i print the output, it was still 1, 2, 3.

I thought that it could be a local variable problem so i tried to fix by add * to head:

n->next = *head;
//Set head
*head = n;

But the compiler said that

assigning to 'struct node *' from incompatible type 'node' (aka 'struct node'); remove *

Can someone help me to explain what happened here ? Thank you very much.

  • You should make the argument a pointer to what to modify `node **head`. – MikeCAT Jul 18 '22 at 15:52
  • The `head` is a copy which is forgotten on function exit. Another solution is to `return head` and assign by caller. – Weather Vane Jul 18 '22 at 15:52
  • 1
    If argument for `head` were an `int` that you wanted the function to change, how would you accomplish that? – Scott Hunter Jul 18 '22 at 15:52
  • Easiest to implement is to return the new head, call it using `head = insert(head, 4);`. no double-pointer shenanigans – Mat Jul 18 '22 at 15:53

0 Answers0