menu driven program to delete in linked list
#include <iostream>
using namespace std;
class node
{
public:
int data;
node*next;
};
node*head=NULL;
void insertlist(int val)
{
node*temp=new node;
temp->data=val;
if(head==NULL)
{
temp->next=head;
head=temp;
}
else
{
temp->next=head;
head=temp;
}
}
void delete_start()
{
if(head==NULL)
{
cout<<"no element in the list :: nothing to be deleted:"<<endl;
}
else
{
node*temp=new node;
temp=head;
head=head->next;
delete(temp);
}
}
void delete_end()
{
if(head==NULL)
{
cout<<"no element in the list :: nothing to be deleted:"<<endl;
}
else
{
node *temp=new node;
temp=head;
node*ptr=new node;
while(temp->next->next!=NULL)
{
temp=temp->next;
}
ptr=temp->next;
temp->next=NULL;
delete ptr;
}
}
void delete_any(int val)
{
node*temp=new node;
if(head==NULL)
{
cout<<"no element in the list :: nothing to be deleted:"<<endl;
}
else
{
if(head->data==val)
{
temp=head;
head=head->next;
delete temp;
}
else
{
node*ptr=new node;
ptr=head;
while(ptr->next!=NULL)
{
if(ptr->next->data==val)
{
temp=ptr->next;
ptr->next=ptr->next->next;
delete temp;
}
ptr=ptr->next;
}
}
}
}
void printf()
{
node*temp=new node;
temp=head;
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp=temp->next;
}
cout<<endl;
}
int main()
{
int n;
int t;
cin>>t;
while(t--)
{
cout<<"enter the value to be inserted in the list:"<<endl;
cin>>n;
insertlist(n);
}
printf();
int s;
while(1)
{
cout<<"1-delete from the start"<<endl<<"2-delete from the end"<<endl<<"3-delete any element"<<endl<<"4-exit"<<endl;
cout<<"enter your choice:"<<endl;
cin>>s;
switch(s)
{
case 1:
{
delete_start();
printf();
break;
}
case 2:
{
delete_end();
printf();
break;
}
case 3:
{
int a;
printf();
cout<<"enter the value to be deleted:"<<endl;
cin>>a;
delete_any(a);
printf();
break;
}
case 4:
{
exit(0);
}
default:
{
cout<<"invalid opertaion:"<<endl;
}
}
}
return 0;
}