here is an improved version of the above code which can be used to delete from any position i.e. head node, middle, or the last node::: your code is right but the complexity in the while loop is making it problematic
Code:
#include <stdio.h>
#include <stdlib.h>
#include<conio.h>
struct node{
int data;
struct node *next;
};
void main()
{
struct node *head, *tail, *temp,*s,*ptrl,*p;
int n,f,i=0;
char ch;
head=tail=NULL;
printf("want to enter data (y/n)\n");
scanf("%c",&ch);
if(ch=='y'||ch=='Y'){
printf("enter your data: \n");
scanf("%d",&n);
fflush(stdin);
tail=(struct node *)malloc(sizeof(struct node));
tail->data=n;
tail->next=NULL;
head=tail;
printf("\nwant to enter more data (y/n)");
scanf("%c",&ch);
fflush(stdin);
}
while(ch=='y'||ch=='Y'){
printf("\nenter your data: ");
scanf("\n%d",&n);
fflush(stdin);
temp=(struct node *)malloc(sizeof(struct node));
tail->next=temp;
temp->data=n;
temp->next=NULL;
tail=temp;
printf("\nwant to enter more data (y/n)");
scanf("\n%c",&ch);
fflush(stdin);
}
printf("\nYour Link list is :\n");
p=head; while(p!=NULL){
printf("%d ",p->data);
p=p->next;
}
printf("\nenter the data you want to delete :");
scanf("\n%d",&f);
ptrl=head;
s=head;
if(s->data==f)
{
head=s->next;
i=1;
}
else
{
while(s->next!=NULL)
{ ptrl=s;
s=s->next;
if(s->data==f)
{
ptrl->next=s->next;i=1;
}
}
}
p=head;
if(i==1){
printf("linked list after deletion is: ");
while(p!=NULL){
printf("%d ",p->data);
p=p->next;
}
}
else{
printf("\ndata not found");
}
getch();
}