【发布时间】:2018-04-05 09:46:05
【问题描述】:
我的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;
}
【问题讨论】:
-
您对
first是否为空的测试被反转(第一个除外)。 -
在
main()的开头,有struct node * temp = first;语句将NULL分配给temp。由于在while循环中,您正在打印列表,因此在while循环之前您应该将first分配给temp。
标签: c linked-list singly-linked-list