C program linked list code not running

#include<stdio.h>
#include<stdlib.h>
int main(){
struct node{
int data;
struct nodenext;
};
struct node
head=NULL,*new_node,temp;
int choice;
while(choice){
new_node=(struct node
)malloc(sizeof(struct node));
scanf("%d",&new_node->data);
new_node->next=0;
if(head==0)
{
head=temp=new_node;
}
else
{
temp->next=new_node;
temp=new_node;
}
printf(“do you want to continue”);
scanf("%d",&choice);
}
temp=head;
while(temp!=0)
{
printf("%d",temp->data);
temp=temp->next;
}

}

Hey @supratik260699

  1. Some changes you need to make in your code are:

You should initially set the choice variable to 1 if it initially always takes input, else include
scanf("%d",&choice);
before your while(choice) loop to scan the initial choice.

  1. Secondly, as you want to insert the subsequent elements at the head of the linked list,
    so the following statements are wrong:
    else
    {
    temp->next=new_node;
    temp=new_node;
    }
    instead you should write:
    else {
    new_node->next = head;
    head = new_node;
    }

this makes a new_node, appends the head after this new_node so that this new_node is inserted in the beginning and updates the head to new_node because now that is the new head

1 Like