PROGRAM TO DELETE A SPECIFIC ELEMENT FROM THE LINKED LIST

/*PROGRAM TO DELETE A SPECIFIC ELEMENT FROM THE LINKED LIST*/
#include<conio.h>
#include<iostream.h>
struct node
{
int data;
struct node *link;
};
void main()
{
struct node *start=NULL,*ptr,*temp,*ptr1,*ptr2;
int num,item;
char ch;
clrscr();
cout<<“Inserting elements in the list:”<<endl;
do
{
temp=new node;
cout<<“Enter element: “;
cin>>num;
temp->data=num;
if(start==NULL)
{
start=temp;
start->link=NULL;
}
else
{
temp->link=start;
start=temp;
}
cout<<“Do you want to continue?? “;
cin>>ch;
}while(ch==’y’||ch==’Y’);
cout<<“Elements in the list are:”<<endl;
for(ptr=start;ptr!=NULL;ptr=ptr->link)
{
cout<<ptr->data<<“\t”;
}
cout<<endl<<“Do you want to perform deletion?? “;
cin>>ch;
if(ch==’y’||ch==’Y’)
{
do
{
if(start==NULL)
{
cout<<“!!List is empty!!”;
break;
}
cout<<“Enter the value: “;
cin>>item;
if(item==start->data)
{
cout<<“Deleted element is: “<<start->data<<endl;
start=start->link;
}
else
{
ptr1=start;
ptr2=start->link;
while(ptr2!=NULL)
{
if(ptr2->data==item)
{
cout<<“Deleted element is: “<<ptr2->data<<endl;
ptr1->link=ptr2->link;
break;
}
ptr1=ptr2;
ptr2=ptr2->link;
}

if(ptr2==NULL)
cout<<“!!Number not found!!”<<endl;
}
if(start!=NULL)
{
cout<<“Remaining elements in the list are:”<<endl;
for(ptr=start;ptr!=NULL;ptr=ptr->link)
{
cout<<ptr->data<<“\t”;
}
}
cout<<endl<<“Do you want to continue?? “;
cin>>ch;
}while(ch==’y’||ch==’Y’);
if(start!=NULL)
{
cout<<“Remaining elements in the list are:”<<endl;
for(ptr=start;ptr!=NULL;ptr=ptr->link)
{
cout<<ptr->data<<“\t”;
}
}
}
else
cout<<“!!Press any key to exit!!”;
getch();
}

Leave a Reply

Your email address will not be published. Required fields are marked *