Created
April 27, 2018 06:49
-
-
Save Zyro9922/658226548c5f0a231bfd738f3c252b40 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
using namespace std; | |
class Node{ | |
public: | |
int data; | |
Node* next; | |
Node(int x) | |
{ | |
data = x; | |
next = NULL; | |
} | |
}; | |
Node* createLL(int n) | |
{ | |
Node* head = NULL; | |
Node* tail = NULL; | |
int i = 0; | |
while(i!=n) | |
{ | |
int x; | |
cin>>x; | |
Node* cur = new Node(x); | |
if(head == NULL) | |
{ | |
head = cur; | |
tail = cur; | |
} | |
else | |
{ | |
tail->next = cur; | |
tail = cur; | |
} | |
i++; | |
} | |
return head; | |
} | |
void display(Node* head){ | |
Node* cur = head; | |
while(cur != NULL){ // while(cur) | |
cout << cur->data << " "; | |
cur = cur->next; | |
} | |
} | |
Node* mergeSortedLL(Node* head1, Node* head2) | |
{ | |
Node* head = NULL; | |
Node* cur = NULL; | |
Node* tail = NULL; | |
int ele1=0,ele2=0; | |
if(head1) | |
ele1 = head1->data; | |
if(head2) | |
ele2 = head2->data; | |
while(head1 && head2) | |
{ | |
if(ele2 > ele1) | |
{ | |
cur = new Node(ele1); | |
if(head == NULL) | |
{ | |
head = cur; | |
tail = cur; | |
} | |
else | |
{ | |
tail->next = cur; | |
tail = cur; | |
} | |
if(head1->next==NULL) | |
break; | |
head1 = head1->next; | |
ele1 = head1->data; | |
} | |
else | |
{ | |
cur = new Node(ele2); | |
if(head == NULL) | |
{ | |
head = cur; | |
tail = cur; | |
} | |
else | |
{ | |
tail->next = cur; | |
tail = cur; | |
} | |
if(head2->next == NULL) | |
break; | |
head2 = head2->next; | |
ele2 = head2->data; | |
} | |
} | |
if(head1 && head2->next==NULL) | |
{ | |
while(head1) | |
{ | |
tail->next = head1; | |
tail = head1; | |
head1 = head1->next; | |
} | |
} | |
else if(head2 && head1->next == NULL) | |
{ | |
while(head2) | |
{ | |
tail->next = head2; | |
tail = head2; | |
head2 = head2->next; | |
} | |
} | |
return head; | |
} | |
int main() | |
{ | |
int t; | |
cin>>t; | |
while(t!=0) { | |
int n; | |
cin>> n; | |
Node* head1 = createLL(n); | |
int m; | |
cin>> m; | |
Node* head2 = createLL(m); | |
Node* head = mergeSortedLL(head1, head2); | |
display(head); | |
t--; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment