10. Write a menu driven program to implement the following operations in an ordered linked list:
a) Insertion
b) Deletion
c) Merging
--------------------------------------------------------------------------------------------------------------------
#include<iostream>
using namespace std;
class node
{
public:
int data;
node *next;
};
class olist
{
node *first;
int n;
public:
olist()
{
first=NULL;
}
void create()
{
char ch;
first=new node;
cout<<"Enter data for first node:\n";
cin>>first->data;
first->next=NULL;
do
{
cout<<"Want to enter more data:\n";
cin>>ch;
if(ch=='y')
{
insert();
}
}while(ch=='y');
}
void insert()
{
node *current,*temp,*prev;
temp=new node;
cout<<"Enter data:\n";
cin>>temp->data;
int b=temp->data;
temp->next=NULL;
prev=NULL;
current=first;
while((current!=NULL)&&((current->data)<b))
{
prev=current;
current=current->next;
}
if(prev==NULL)
{
temp->next=first;
first=temp;
}
else if(current==NULL)
{
prev->next=temp;
//temp->next=NULL;
}
else
{
temp->next=current;
prev->next=temp;
}
}
void search()
{
int flag=0;
cout<<"Enter data to be searched:\n";
cin>>n;
node *current,*prev,*temp;
int b=count();
current=first;
for(int i=1;i<=b;i++)
{
if(current->data==n)
{
flag=1;
break;
}
prev=current;
current=current->next;
}
if(flag==1)
{
int c;
cout<<"Data found:\nEnter what you wannna do:\n 1.delete data\n 2.replace it\n 3.do nothing\n";
cin>>c;
switch(c)
{
case 1:temp=current;
prev->next=current->next;
delete(temp);
cout<<"Data deleted:\n";
break;
case 2:cout<<"Enter new data:\n";
cin>>current->data;
cout<<"data replaced:\n";
break;
case 3:break;
default:cout<<"wrong choice:\n";
}
}
else
cout<<"Data not found:\n";
}
//overloading + operator
olist* operator +(olist l1)
{
olist l2;
l2.first=first;
node *current;
current=l2.first;
while(current->next!=NULL)
current=current->next;
current->next=l1.first;
return this;
}
void display()
{
node *current;
current=first;
while(current!=NULL)
{
cout<<current->data<<" -> ";
current=current->next;
}
cout<<endl;
}
int count()
{
node *current;
int c=0;
current=first;
while(current!=NULL)
{
c++;
current=current->next;
}
return c;
}
};
int main()
{
olist l1,l2;
l1.create();
l1.display();
l1.search();
cout<<"Now enter data for list 2:\n";
l2.create();
l2.display();
l2.search();
olist *l3=l1+l2;
l3->display();
}
--------------------------------------------------------------------------------------------------------------------
Program Finish.........