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.