Time limit exceeded please make efficient correctin

#include

using namespace std;
class node
{ public:
int data;
node*next;
};

void insertattail(node*&head,int data)
{
if(head==NULL)
{
nodetemp=new node;
temp->data=data;
temp->next=head;
head=temp;
}
else
{
node
temp=head;
while(temp->next!=NULL)
{

        temp=temp->next;
    }
    node*n=new node;
    temp->next=n;
    n->next=NULL;
    n->data=data;

}

}
void linkedlist(node*&head,int n)
{
for(int i=0;i<n;i++)
{
int data;
cin>>data;
insertattail(head,data);
}
}
node* merge(node*&head1,node*&head2)
{
nodep=head1;
node
q=head2;
nodesorting=NULL;
if(p==NULL)
{
return q;
}
else if(q==NULL)
{
return p;
}
else
{
if(p->datadata)
{
sorting=p;
p=sorting->next;
}
else
{
sorting=q;
q=sorting->next;
}
}
node
new_head=sorting;
while(p!=NULL&&q!=NULL)
{
if(p->datadata)
{
sorting->next=p;
sorting=p;
p=sorting->next;
}
else
{
sorting->next=q;
sorting=q;
q=sorting->next;
}
}
if(p==NULL)
{
sorting->next=q;
}
else
{
sorting->next=p;
}
return new_head;

}
void print(node*head)
{

if(head==NULL)
{
    return;
}

else{
    while(head!=NULL)
    {
        cout<<head->data<<" ";
        head=head->next;
    }
}

}
int main() {
nodehead1=NULL;
node
head2=NULL;
int t;
cin>>t;
for(int i=0;i<t;i++)
{
int n1,n2;
cin>>n1;

linkedlist(head1,n1);
cin>>n2;
linkedlist(head2,n2);
node*head=merge(head1,head2);
print(head);
}

}

There are few errors in your code, kindly rectify them, firstly use this algorithm in the merge sort function of your code, as :
node *merge(node *a,node *b)
{
if(a==NULL)
{
return b;
}
if(b==NULL)
{
return a;
}
node *c;
if(a->datadata)
{
c=a;
c->next=merge(a->next,b);
}
else
{
c=b;
c->next=merge(a,b->next);
}
return c;
}

Also, I have made some changes in your original code apart from the sorted function that you need to use, kindly see to tht also,

Please send the link of your code.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.