Merge two sorted Linked Lists
You have been given two sorted(in ascending order) singly linked lists of integers.
Write a function to merge them in such a way that the resulting singly linked list is also sorted(in ascending order) and return the new head to the list.
Note :
Input format :
Remember/Consider :
Output :
Constraints :
Sample Input 1 :
Sample Output 1 :
Sample Input 2 :
Sample Output 2 :
/****************************************************************
Following is the class structure of the Node class:
class Node
{
public:
int data;
Node *next;
Node(int data)
{
this->data = data;
this->next = NULL;
}
};
*****************************************************************/
void display(Node* head){
Node* temp=head;
while(temp!=NULL){
cout<<temp->data<<" ";
temp=temp->next;
}
}
#include <bits/stdc++.h>
Node *mergeTwoSortedLinkedLists(Node *head1, Node *head2)
{
//Write your code here
if (head1==NULL and head2==NULL){
return head1;
}
if (head1==NULL){
return head2;
}
if(head2==NULL){
return head1;
}
if (head1->data>head2->data){
swap(head1,head2);
}
// display(head1);
// display(head2);
Node*ft=head1;
Node*fh=head1;
Node* temp=head1;
Node* temp1=head1;
Node* temp2=head2;
temp1=temp1->next;
while(temp1!=NULL && temp2!=NULL){
if(temp1->data<=temp2->data){
ft->next=temp1;
ft=temp1;
temp1=temp1->next;
}
else
{
ft->next=temp2;
ft=temp2;
temp2=temp2->next;
}
}
if (temp1!=NULL){
ft->next=temp1;
// ft=temp1;
}
if (temp2!=NULL){
ft->next=temp2;
// ft=temp2;
}
return fh;
}
Comments
Post a Comment