I have a problem with my add_to_list
function here.
I'm using this function to add a node to the begging of the singly linked list that referenced by list pointer.
The problem is: only the first node is added, then if I add any more, I lose the trace of the 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;
}
So at the beginning of main
you've got these two lines...
struct node * first = NULL;
struct node * temp = first;
...which assign NULL
to first
and then the value of first
to temp
which means both of them are NULL
. This is a one time assignment - temp
won't get updated as first
changes.
When you get to the bottom of the function you have this loop, but nothing has updated the value of temp
since it was first assigned NULL
.
while(temp!=NULL){
printf("%d-->",(temp->value));
temp = temp ->next;
}
The solution is to assign the current value of first
to temp
just before the loop like so:
temp = first;
while(temp!=NULL){
printf("%d-->",(temp->value));
temp = temp ->next;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments