Merge Two Sorted Linked List

This is the function for merging two sorted linked list
Node* sortedMerge(Node* head1, Node* head2)
{
Node *dummy=new Node(0);
Node *temp=dummy;
while(1)
{
if(head1->next!=NULL)
{
temp->next=head2;
break;
}
if(head2->next!=NULL)
{
temp->next=head1; break;
}
if(head1->datadata)
{
temp->next =head1;
temp=temp->next;
head1=head1->next;
}
else
{
temp->next=head2;
temp=temp->next;
head2=head2->next;
}
}
return dummy;
}

Could you please suggest How to avoid zero

This Code Works fine

Node *dummy=new Node(0);
Node *temp=dummy,*temp2=dummy;
if(head1->data < head2->data)
temp2=head1;
else
temp2=head2;
while(1)
{
if(head1==NULL)
{
temp->next=head2;
break;
}
if(head2==NULL)
{
temp->next=head1; break;
}
if(head1->datadata)
{
temp->next =head1;
temp=temp->next;
head1=head1->next;
}
else
{
temp->next=head2;
temp=temp->next;
head2=head2->next;
}
}
return temp2;
}

2 Likes

In the first code, for the if loops I think you need to use “==” instead of “!=”.