EASIEST WAY FOR MERGE TWO LINKLIST
/* Link list Node
struct Node {
int data;
Node* next;
}; */
Node* SortedMerge(Node* head1, Node* head2)
{
struct Node *head,*last;
if(head1==NULL)
{
return head2;
}
if(head2==NULL)
{
return head1;
}
if(head1&&head2)
{
if(head1->data<head2->data)
{
last=head1;
head1=last->next;
}
else
{
last=head2;
head2=last->next;
}
}
head=last;
while(head1&&head2)
{
if(head1->data<head2->data)
{
last->next=head1;
last=head1;
head1=last->next;
}
else
{
last->next=head2;
last=head2;
head2=last->next;
}
}
if(head1)
{
last->next=head1;
}
if(head2)
{
last->next=head2;
}
return head;
}
struct Node {
int data;
Node* next;
}; */
Node* SortedMerge(Node* head1, Node* head2)
{
struct Node *head,*last;
if(head1==NULL)
{
return head2;
}
if(head2==NULL)
{
return head1;
}
if(head1&&head2)
{
if(head1->data<head2->data)
{
last=head1;
head1=last->next;
}
else
{
last=head2;
head2=last->next;
}
}
head=last;
while(head1&&head2)
{
if(head1->data<head2->data)
{
last->next=head1;
last=head1;
head1=last->next;
}
else
{
last->next=head2;
last=head2;
head2=last->next;
}
}
if(head1)
{
last->next=head1;
}
if(head2)
{
last->next=head2;
}
return head;
}
Comments
Post a Comment