/*write a c program to delete all the nodes in a signly linked
list which have value N.
*/
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
struct node
{
int data;
struct node *next;
}*start=NULL,*q,*temp;
int cnt=0,p,n,end;
void create();
void display();
void count();
void delete();
int pos();
void main()
{
char ch='y';
int choice;
clrscr();
while(ch=='y'||ch=='Y')
{
create();
printf("\ndo you want to continue(Y|N):-");
scanf("\n%s",&ch);
}
display();
count();
delete();
display();
getch();
}
void create()
{
temp=malloc(sizeof(struct node));
printf("\nenter the number:-");
scanf("%d",&temp->data);
temp->next=NULL;
if(start==NULL)
start=temp;
else
{
q=start;
while(q->next!=NULL)
{
q=q->next;
}
q->next=temp;
}
}
void display()
{
if(start==NULL)
printf("\nlinked list is empty");
else
{
printf("\nelement in singly linked list are:-\n");
q=start;
while(q!=NULL)
{
printf("%d\n",q->data);
q=q->next;
}
}
}
void count()
{
struct node *q;
cnt=0;
if(start==NULL)
printf("\nlinked list is empty");
else
{
q=start;
while(q!=NULL)
{
cnt++;
q=q->next;
}
}
}
void delete()
{
int i,tno=0;
printf("\nenter number which you want to delete:-");
scanf("%d",&n);
i=0;
q=start;
count();
tno=cnt;
while(i<tno)
{
if(start->data==n)
{
temp=start;
start=start->next;
free(temp);
}
i++;
}
i=0;
while(i<tno)
{
q=start;
end=pos();
if(end==1)
break;
else
{
for(i=0;i<end-2;i++)
{
q=q->next;
}
temp=q->next;
q->next=temp->next;
free(temp);
q=q->next;
i++;
}
}
}
int pos()
{
struct node *q;
p=1;
if(start==NULL)
printf("\nlinked list is empty");
else
{
q=start;
while(q->next!=NULL)
{
q=q->next;
if(q->data==n)
{
p=p+1;
return p;
}
else
p=p+1;
}
}
return 1;
}
/*
enter the number:-5
do you want to continue(Y|N):-y
enter the number:-5
do you want to continue(Y|N):-y
enter the number:-7
do you want to continue(Y|N):-y
enter the number:-5
do you want to continue(Y|N):-y
enter the number:-3
do you want to continue(Y|N):-y
enter the number:-5
do you want to continue(Y|N):-y
enter the number:-5
do you want to continue(Y|N):-n
element in singly linked list are:-
5
5
7
5
3
5
5
enter number which you want to delete:-5
element in singly linked list are:-
7
3
*/
No comments:
Post a Comment