PROGRAM TO MERGE TWO DOUBLY LINKED LISTS

/*PROGRAM TO MERGE TWO DOUBLY LINKED LISTS*/
#include<conio.h>
#include<iostream.h>
struct node
{
int data;
struct node *flink,*plink;
};
void main()
{
struct node *start=NULL,*start1=NULL,*ptr,*temp,*temp1,*ptr1,*ptr2;
int num;
char ch;
clrscr();
cout<<“Inserting elements in the first list: “<<endl;
do
{
temp=new node;
cout<<“Enter the element: “;
cin>>num;
temp->data=num;
if(start==NULL)
{
start=temp;
start->plink=NULL;
start->flink=NULL;
}
else
{
temp->flink=start;
temp->plink=NULL;
start->plink=temp;
start=temp;
}
cout<<“Do you want to continue?? “;
cin>>ch;
}while(ch==’y’);
cout<<“Forward traversing of elements: “<<endl;
for(ptr=start;ptr->flink!=NULL;ptr=ptr->flink)
{
cout<<ptr->data<<“\t”;
}
cout<<ptr->data<<endl;

cout<<“Backward traversing of elements: “<<endl;
for(ptr1=ptr;ptr1!=NULL;ptr1=ptr1->plink)
{
cout<<ptr1->data<<“\t”;
}
cout<<endl<<“Inserting elements in the second list: “<<endl;
do
{
temp=new node;
cout<<“Enter the element: “;
cin>>num;
temp->data=num;
if(start1==NULL)
{
start1=temp;
start1->plink=NULL;
start1->flink=NULL;
}
else
{
temp->flink=start1;
temp->plink=NULL;
start1->plink=temp;
start1=temp;
}
cout<<“Do you want to continue?? “;
cin>>ch;
}while(ch==’y’);
cout<<“Forward traversing of elements: “<<endl;
for(ptr=start1;ptr->flink!=NULL;ptr=ptr->flink)
{
cout<<ptr->data<<“\t”;
}
cout<<ptr->data<<endl;
cout<<“Backward traversing of elements: “<<endl;
for(ptr1=ptr;ptr1!=NULL;ptr1=ptr1->plink)
{
cout<<ptr1->data<<“\t”;
}
//MERGING TWO LISTS
ptr=start;
while(ptr->flink!=NULL)
{
ptr=ptr->flink;
}
ptr->flink=start1;
start1->plink=ptr;
cout<<endl<<“After merging: “<<endl;
cout<<“Forward traversing of list: “<<endl;
for(ptr=start;ptr->flink!=NULL;ptr=ptr->flink)
{
cout<<ptr->data<<“\t”;
}
cout<<ptr->data<<endl;
cout<<“Backward traversing of list: “<<endl;
for(ptr1=ptr;ptr!=NULL;ptr=ptr->plink)
{
cout<<ptr->data<<“\t”;
}
getch();
}

Leave a Reply

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