Getting two merged address

i am storing the address of merged LL in head3 but on displaying data using head its giving merged output

check the code

#include
using namespace std;

class node {
public:
int data;
node *next;
node(int data){
this->data=data;
next=NULL;
}
};

void insert(node *&head,int data){
node *t = new node(data);
node *ptr=head;
if(head==NULL){
head=t;
}
else{
while(ptr->next){
ptr=ptr->next;
}
ptr->next=t;
}
}

void disp(node *ptr){
while(ptr){
cout<data<<" ";
ptr=ptr->next;
}
}

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->next=merge(a->next,b);
}
else{
c=b;
c->next=merge(b->next,a);
}
return c;
}

int main() {
node *head=NULL;
node *head2=NULL;
int n1;
cin>>n1;
for(int i=0;i<n1;i++){
int num;
cin>>num;
insert(head,num);
}
int n2;
cin>>n2;
for(int i=0;i<n2;i++){
int num;
cin>>num;
insert(head2,num);
}
node *head3;
head3 = merge(head,head2);
disp(head);
}

Hey
Change it to disp(head3), will show correct output.
Also, in line no 30, write cout << ptr->data instead of data

See it shows the correct ans even while displaying head because, in the test case given, head had a smaller value than head2, so head was altered and assigned to c and returned as per the logic of the merge function

but in merge function we are passing the copy of head , head2 address , and storing the return value in head3 . so how the address of head is getting altered.

Hey
Yeah, may be it happens because they’re all pointers, so appending changes them at the address as well, so you don’t need to worry about that, head3 should be storing the correct merged linked list, you have to verify that only.

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.