I,m writing a C code for implementing and traversing a Linked list with a while loop. I'm unable to figure out what I wrote wrong in code. The code instead of terminating in while (a,=NULL) and displaying all the elements in the linked list.it goes into an infinite loop. here is the code.....
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node * next;
};
void Display(struct node * a){
printf("The elements are :");
while(a!=NULL){
printf("%d\n",a->data);
a=a->next;
}
}
int main(){
int choice;
struct node * head, * new_node, * temp;
head = NULL; // head points to NULL
new_node=(struct node*)malloc(sizeof(struct node));
while(choice){
printf("Enter the Data");
scanf("%d", &new_node->data); // Entering value in new_node
new_node->next=NULL;
if (head == NULL)
{
head = temp = new_node;
}
else
{
temp->next = new_node;
temp = new_node;
}
printf("Enter 0 for ending and 1 for continuing");
scanf("%d", &choice);
}
Display(head);
return 0;
}
Output: enter the data1 enter 0 for ending and 1 for continuing 1 enter the data 2 enter 0 for ending and 1 for continuing 1 enter the data 3 enter 0 for ending and 1 for continuing 0 3
3
3
3
3
3
3
...... not terminating
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node * next;
};
void Display(struct node * a){
printf("The elements are :");
while(a!=NULL){
printf("%d\n",a->data);
a=a->next;
}
}
int main(){
int choice;
struct node * head, * temp;
head = NULL; // head points to NULL
while(choice){
struct node *new_node=(struct node*)malloc(sizeof(struct node));
printf("Enter the Data");
scanf("%d", &new_node->data); // Entering value in new_node
new_node->next=NULL;
if (head == NULL)
{
head = temp = new_node;
}
else
{
temp->next = new_node;
temp = new_node;
}
printf("Enter 0 for ending and 1 for continuing");
scanf("%d", &choice);
}
Display(head);
return 0;
}
According to Eugene Sh , this code will work
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.