PROGRAM TO DELETE AN ELEMENT FROM THE END OF LINKED LIST

/*PROGRAM TO DELETE AN ELEMENT FROM THE END OF 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;
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 now!!”<<endl;
break;
}
else
{
ptr1=start;
ptr2=start->link;
while(ptr2->link!=NULL)
{
ptr1=ptr2;
ptr2=ptr2->link;
}
if(ptr2!=NULL)
{
cout<<“Deleted element is: “<<ptr2->data<<endl;
ptr1->link=NULL;
}
else
{
cout<<“Deleted node is: “<<ptr1->data<<endl;
start=NULL;
}
}
cout<<“Do you want to continue?? “;
cin>>ch;
}while(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 *