caddy-caddy
caddy-caddy

Reputation: 205

Adding a new node to the end of a linked list in C

I have to add a new node to the end of a linked list. Now I got an error "Item nr. 1 incorrectly has NULL as next pointer". I understand that for the first call of the function the first node (start) is set to NULL, but I don't know how to write this function approptiately then.

struct product *add_product(struct product *start, int price) {

struct product *new_node, *temp;

new_node = malloc(sizeof(struct product));

new_node->next = NULL;

new_node->price = price;

if (start == NULL){
   start = new_node;
}

else{
   for (temp = start; temp->next != NULL; temp = temp->next)
   temp->next = new_node;   
}

temp = new_node;

return new_node;
}

I would greatly appreciate your help.

Upvotes: 1

Views: 77

Answers (1)

Gopi
Gopi

Reputation: 19864

for (temp = start; temp->next != NULL; temp = temp->next)

should be

for (temp = start; temp->next != NULL; temp = temp->next);

Then you reach the end of the linked list and add a node there

if(start == NULL)
{
     start = new_node;
     return start;
}
temp = start;

while(temp->next != NULL)
temp = temp->next;

temp->next = new_node;

return start; // Return head

Upvotes: 2

Related Questions