this is a challenge for merging two sorted linked lists. it is showing TLE error. what else can I do?
here is the code:-
#include
using namespace std;
class node{
public:
int data;
node *link;
};
void makelist(node *&head,int n);
void printlist(node *head);
void insert_last(node &head,int d);
node merge(node *a,node *b);
int main()
{
node *head1=NULL;
node *head2=NULL;
int t,n1,n2;
cin>>t;
while(t–)
{
cin>>n1;
makelist(head1,n1);
cin>>n2;
makelist(head2,n2);
printlist(merge(head1,head2));
}
return 0;
}
//end of main
void makelist(node *&head,int n)
{
int i,d;
for(i=0;i<n;i++)
{
cin>>d;
insert_last(head,d);
}
return;
}
//end of makelist
void insert_last(node *&head,int d)
{node *temp=new node;
temp->data=d;
if(head==NULL)
{
temp->link=head;
head=temp;
}
node *wand=head;
while(wand->link!=NULL)
{
wand=wand->link;
}
wand->link=temp;
temp->link=NULL;
return;
}
//end of insert_last
void printlist(node *head)
{
while(head !=NULL)
{
cout<data<<" ";
head=head->link;
}
cout<<endl;
return;
}
//end of printlist’
node* merge(node *a, node *b)
{
if(a==NULL)
{
return b;
}
if(b==NULL)
{
return a;
}
node *c;
if(a->data<b->data)
{
c=a;
c->link=merge(a->link,b);
}
else
{
c=b;
c->link=merge(a,b->link);
}
return c;
}