#include<iostream>
using namespace std;
struct node
{
int info;
struct node *link;
};
typedef struct node* NODE;
class sll
{
public :
NODE getnode();
void freenode(NODE x);
NODE insert_front(int item,NODE first);
NODE delete_front(NODE first);
NODE insert_rear(int item,NODE first);
NODE delete_rear(NODE first);
void display(NODE first);
};
NODE sll:: getnode()
{
NODE x;
x= new(struct node);
if(x==NULL)
{
cout<<"Insufficient Memory\n";
exit(0);
}
return x;
}
void sll:: freenode(NODE x)
{
delete x;
}
NODE sll:: insert_front(int item,NODE first)
{
NODE temp;
temp=getnode();
temp->info=item;
temp->link=first;
first=temp;
return first;
}
NODE sll:: delete_front(NODE first)
{
NODE temp;
if(first == NULL)
{
cout<<"List is empty and cannot delete";
return first;
}
temp = first;
first = first->link;
cout<<"Item Deleted="<<temp->info;
freenode(temp);
return first;
}
NODE sll:: insert_rear(int item,NODE first)
{
NODE temp;
NODE cur;
temp=getnode();
temp->info=item;
temp->link=NULL;
if(first==NULL)
{
return temp;
}
cur=first;
while(cur->link != NULL)
{
cur=cur->link;
}
cur->link=temp;
return first;
}
NODE sll:: delete_rear(NODE first)
{
NODE cur,prev;
if(first == NULL)
{
cout<<"List is empty and cannot be deleted\n";
return first;
}
prev=NULL;
cur=first;
if(cur->link == NULL)
{
cout<<"The item to be deleted is \n"<<cur->info;
freenode(cur);
return first;
}
while(cur->link != NULL)
{
prev=cur;
cur=cur->link;
}
cout<<"The item deleted is "<<cur->info;
freenode(cur);
prev->link=NULL;
return first;
}
void sll:: display(NODE first)
{
NODE temp;
if(first==NULL)
{
cout<<"LIST IS EMPTY\n";
}
cout<<"The contents of single linked list are \n";
temp=first;
while(temp != NULL)
{
cout<<" "<<temp->info;
temp=temp->link;
}
cout<<endl;
}
int main()
{
sll obj;
NODE first=NULL;
int choice,item ;
for(;;)
{
cout<<"\n1.Insert front 2.delete front 3.Insert rear 4.Delete rear
5.Display 6.Quit\n";
cout<<"\nEnter your choice::";
cin>>choice;
switch(choice)
{
case 1: cout<<"Enter the item to be inserted\n";
cin>>item;
first=obj.insert_front(item,first);
break;
case 2: first = obj.delete_front(first);
break;
case 3: cout<<"Enter the item to be inserted\n";
cin>>item;
first=obj.insert_rear(item,first);
break;
case 4: first = obj.delete_rear(first);
break;
case 5: obj.display(first);
break;
case 6: exit(0);
default:cout<<"INVALID CHOICE\n";
}
}
return 0;
}