fork download
  1. #include<iostream>
  2. using namespace std;
  3. class node{
  4. public:
  5. node *next;
  6. int data;
  7. node(int d){
  8. next = NULL;
  9. data = d;
  10. }
  11. };
  12. void insertAtTail(node *&head, int data){
  13. if(head==NULL){
  14. head= new node(data);
  15. return;
  16. }
  17. node *temp = head;
  18. while(temp->next!=NULL){
  19. temp = temp->next;
  20. }
  21. temp->next = new node(data);
  22. return;
  23. }
  24. node *buildInput(node *&head, int n){
  25. int data;
  26. for(int i=0;i<n;i++){
  27. cin>>data;
  28. insertAtTail(head,data);
  29. }
  30. return head;
  31. }
  32. void print(node *head){
  33. while(head !=NULL){
  34. cout<< head->data<<" ";
  35. head = head->next;
  36. }
  37. }
  38. node *merge(node *a, node *b){
  39. if(a==NULL)
  40. return b;
  41. else if(b==NULL){
  42. return a;
  43. }
  44. node *c;
  45. if(a->data < b->data){
  46. c=a;
  47. c->next = merge(a->next,b);
  48. }
  49. else{
  50. c=b;
  51. c->next = merge(a,b->next);
  52. }
  53. return c;
  54. }
  55. int main(){
  56. node *head = NULL;
  57. int t,n1,n2;
  58. cin>>t;
  59.  
  60. for(int i=0;i<t;i++){
  61. cin>>n1;
  62. node *head1 = buildInput(head,n1);
  63. cin>>n2;
  64. node *head2 = buildInput(head,n2);
  65.  
  66. node *ans = merge(head1,head2);
  67. print(ans);
  68. }
  69.  
  70. return 0;
  71. }
  72.  
Success #stdin #stdout 0s 4188KB
stdin
Standard input is empty
stdout
Standard output is empty