在C中将新节点添加到链接列表的末尾

时间:2021-02-20 07:16:02

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.

我必须在链表的末尾添加一个新节点。现在我收到一个错误“Item nr.1错误地将NULL作为下一个指针”。我理解,对于函数的第一次调用,第一个节点(start)设置为NULL,但我不知道如何适当地编写这个函数。

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.

非常感谢你的帮助。

1 个解决方案

#1


2  

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

#1


2  

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