Here this function is supposed to take care of entry of data in a Singly-Linked List, If there is no item in the list it adds it to the head and after that onwards, This add() function is called on a while loop till the user wants to continue. But this is only adding the first two data and is not working for the rest of the list
struct node{
int data;
struct node *nextptr;
}*head;
int add()
{
struct node *ptr,*tmp;
int value;
ptr=malloc(sizeof(struct node));
if(ptr==NULL)
{
printf("MEMORY ALLOCATION FAILED ");
}
else
{
printf("ENTER THE VALUE YOU WANT TO ENTER ");
scanf("%d",&value);
if(head==NULL)
{
ptr->data=value;
ptr->nextptr=NULL;
head=ptr;
}
else
{ tmp=head;
ptr->data=value;
ptr->nextptr=NULL;
tmp->nextptr=ptr;
ptr=ptr->nextptr;
tmp=tmp->nextptr;
}
}
return 0;
}
Kindly try to tell the problem in this method, I have came across different ways to do the same but I just need to know why it can't be implemented this way.
question from:
https://stackoverflow.com/questions/65651160/the-add-in-function-only-add-two-elements-to-the-list 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…