1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
|
#include<iostream>
#include<assert.h>
using namespace std;
class node
{
public:
node* create(int n);
void Insert(node** head,int n);
void print(node* head);
node* merge(node** head1,node ** head2,node** bar);
private:
node* next;
node* prev;
int data;
};
node* node::create(int n)
{
node* temp=new node;
assert(temp);
temp->data=n;
temp->next=NULL;
temp->prev=NULL;
return temp;
}
void node::Insert(node** head,int n)
{
node* temp=create(n);
if(*head==NULL)
{
*head=temp;
}
else
{
node* foo=(*head);
while(foo->next!=NULL)
{
foo=foo->next;
}
foo->next=temp;
temp->prev=foo;
}
}
node* node::merge(node** head1,node** head2,node** result)
{
//node* foo=NULL;
node* list=*head2;
node* pass=*head1;
if(*head1==NULL)
{
return *head2;
}
else if(*head2==NULL)
{
return *head1;
}
while((*head1)->next!=NULL || (*head2)->next!=NULL)
{
jump:
if((*head1)->data < (*head2)->data){
Insert(result,(*head1)->data);
(*head1)=(*head1)->next;
goto jump;
}
else if((*head1)->data > (*head2)->data){
Insert(result,(*head2)->data);
(*head2)=(*head2)->next;
goto jump;
}
else if((*head1)->data == (*head2)->data){
Insert(result,(*head1)->data);
(*head1)=(*head1)->next;
(*head2)=(*head2)->next;
goto jump;
}
}
return *result;
}
void node::print(node* head)
{
node* temp=head;
if(head==NULL)
{
cout<<"List is Empty!\n";
}
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp=temp->next;
}
cout<<endl;
}
int main()
{
node*head1=NULL,*head2=NULL,*res=NULL;
int m,n;
node ni;
cout<<"Enter size of node 1 ?";
cin>>n;
cout<<"Enter node 1 ?\n";
for(int i=0;i<n;++i)
{
cout<<"Enter element ?";
cin>>m;
ni.Insert(&head1,m);
}
cout<<"Enter size of node 2?";
cin>>n;
cout<<"Enter node 2 ?\n";
for(int i=0;i<n;++i)
{
cout<<"Enter element ?";
cin>>m;
ni.Insert(&head2,m);
}
cout<<"Print node 1 : ";
ni.print(head1);
cout<<"Print node 2 : ";
ni.print(head2);
res=ni.merge(&head1,&head2,&res);
ni.print(res);
}
|