Friday, June 14, 2013

DLL MERGE

DLL MERGE (C++ CODE):



#include<iostream.h>
#include<conio.h>
#include<stdio.h>
class dll
{
private:
struct dnode
{
int data;
struct dnode *next,*prev;
}*start;
public:
dll()
{
start=NULL;
}
void create();
void display();
void sort();
void merge(dll,dll);
};
void dll::create()
{
dnode *new_node,*current;
char ch;
do
{
new_node=new dnode;
cout<<"\nenter the data:";
cin>>new_node->data;
new_node->next=NULL;
new_node->prev=NULL;
if(start==NULL)
{
start=new_node;
current=new_node;
}
else
{
current->next=new_node;
new_node->prev=current;
current=current->next;
}
cout<<"\ndo u want  to add more nodes?";
cin>>ch;
}while(ch=='y'||ch=='Y');
}
void dll::display()
{
dnode *temp;
if(start==NULL)
{
cout<<"\nList is empty";
}
else
{
temp=start;
cout<<"\n list is:";
while(temp!=NULL)
{
cout<<"\t"<<temp->data;
temp=temp->next;
}
}
}
void dll::sort()
{
dnode *temp1,*temp2;
int temp;
if(start==NULL)
{
cout<<"\nCannot sort,....";
}
else
{
temp1=start;
while(temp1!=NULL)
{
temp2=start;
while(temp2->next!=NULL)
{
if(temp2->data>temp2->next->data)
{
temp=temp2->data;
temp2->data=temp2->next->data;
temp2->next->data=temp;
}
temp2=temp2->next;
}
temp1=temp1->next;
}
}
}
void dll::merge(dll a,dll b)
{
dnode *temp1,*temp2,*temp3,*current;
temp1=a.start;
temp2=b.start;
while(temp1!=NULL&&temp2!=NULL)
{
if(temp1->data>temp2->data)
{
temp3=temp2;
temp2=temp2->next;
}
else if(temp1->data<temp2->data)
{
temp3=temp1;
temp1=temp1->next;
}
else
{
temp3=temp1;
temp1=temp1->next;
temp2=temp2->next;
}
if(start==NULL)
{
current=temp3;
start=temp3;
}
else
{
current->next=temp3;
temp3->prev=current;
current=current->next;
}
 }
if(temp1!=NULL)
{
current->next=temp1;
temp1->prev=current;
}
if(temp2!=NULL)
{
current->next=temp2;
temp2->prev=current;
}

}

void main()
{
dll a,b,c;
clrscr();
cout<<"\nenter the first list:";
a.create();
a.sort();
a.display();
cout<<"\nenter the second list:";
b.create();
b.sort();
b.display();
c.merge(a,b);
cout<<"\nList after merge is:";
c.display();
getch();

}


No comments:

Post a Comment

Thanks for your valuable comment