Reputation: 97
If I call createnode(x) in main and then follow that with printNodes(); I will get an infinite while-loop that seems to be printing some memory address. I am guessing the issue lies in the fact that i set head = temp?
SinglyLinkedList *head = NULL;
void createNode(int data){
SinglyLinkedList *temp = malloc(sizeof(SinglyLinkedList));
temp-> data = data;
if(head == NULL){
head = temp;
return;
}
temp->next = head;
head = temp;
}
void printNodes(){
SinglyLinkedList *temp = head;
while ( temp != NULL ){
printf("%d\r\n",temp->data);
temp = temp->next;
}
}
Upvotes: 2
Views: 87
Reputation: 385647
SinglyLinkedList *temp = malloc(sizeof(SinglyLinkedList));
temp->data = data;
if(head == NULL){
head = temp;
return;
}
temp->next = head;
head = temp;
should be
SinglyLinkedList *temp = malloc(sizeof(SinglyLinkedList));
temp->data = data;
temp->next = head; // Moved
if(head == NULL){
head = temp;
return;
}
head = temp;
which is a very complicate way of writing
SinglyLinkedList *temp = malloc(sizeof(SinglyLinkedList));
temp->data = data;
temp->next = head;
head = temp;
Without this fix, printNodes
results in undefined behaviour as a result of the lack of initialization of temp->next
.
Upvotes: 3