我必须在链表的末尾添加一个新节点。现在我得到一个错误“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;
}
非常感谢您的帮助。
最佳答案
for (temp = start; temp->next != NULL; temp = temp->next)
应该是
for (temp = start; temp->next != NULL; temp = temp->next);
然后你到达链表的末尾并在那里添加一个节点
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
关于c - 在 C 中的链表的末尾添加一个新节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29535775/