c - 在 C 中的链表的末尾添加一个新节点

标签 c linked-list

我必须在链表的末尾添加一个新节点。现在我得到一个错误“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/

相关文章:

C 链表纸牌游戏并由于 fatal error 而得到奇怪的结果

java - 这个 for 循环如何翻译成英语?

c++ - 如何将指针 vector 转换为 C++ 中的链表?

c - 试图了解此代码中的函数指针用法

c - bash、sh、ps 在 Linux 中如何工作?

c - 如何检测Arduino中按下按钮的时间?

java - 如何将自定义链表添加方法转换为java中的插入排序方法?

java - Java中过滤掉重复字符

c - 在 C99/C11 中使用预处理器嵌套 goto 标签?

c - 为什么字符串的 scanf/printf 打印不同的东西