我的 add_to_list
函数在这里有问题。
我正在使用此函数将节点添加到列表指针引用的单链表的开头。
问题是:只第一个节点被添加,如果我再添加更多,我就失去了列表的踪迹。
#include <stdio.h>
#include <stdlib.h>
struct node {
int value;
struct node* next;
};
struct node *add_to_list(struct node *list , int n){
struct node *new_node ;
new_node = malloc( sizeof(struct node) ); //create new node
if(new_node == NULL){
printf("Error ,malloc failed to allocate memory\n");
exit(EXIT_FAILURE);
}
new_node->value = n; //initiate value field
new_node->next = list;
return new_node;
}
int main(){
struct node * first = NULL;
struct node * temp = first;
first = add_to_list(first,10);
if(first != NULL)
printf("node added\n");
else
printf("add failed\n");
first = add_to_list(first,20);
if(first == NULL)
printf("node added\n");
else
printf("add failed\n");
first = add_to_list(first,30);
if(first == NULL)
printf("node added\n");
else
printf("add failed\n");
while(temp!=NULL){
printf("%d-->",(temp->value));
temp = temp ->next;
}
return 0;
}
最佳答案
所以在 main
的开头你有这两行...
struct node * first = NULL;
struct node * temp = first;
...将 NULL
分配给 first
然后将 first
的值分配给 temp
这意味着两者其中有 NULL
。这是一次性分配 - temp
不会随着 first
的更改而更新。
当您到达函数的底部时,您会遇到此循环,但自从第一次分配 NULL
以来,没有任何内容更新 temp
的值。
while(temp!=NULL){
printf("%d-->",(temp->value));
temp = temp ->next;
}
解决方案是在循环之前将 first
的当前值分配给 temp
,如下所示:
temp = first;
while(temp!=NULL){
printf("%d-->",(temp->value));
temp = temp ->next;
}
关于c - 在单链表的开头插入节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46913168/