fork(1) download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. #include <bits/stdc++.h>
  5. using namespace std;
  6.  
  7. class Node{
  8. public:
  9. int data;
  10. Node* next;
  11.  
  12. Node(int d){
  13. data = d;
  14. next = NULL;
  15. }
  16. };
  17.  
  18. void insert(Node*& head, int data){
  19. if(head == NULL){
  20. head = new Node(data);
  21. return;
  22. }
  23.  
  24. Node* temp = head;
  25. while(temp->next != NULL){
  26. temp = temp->next;
  27. }
  28. temp->next = new Node(data);
  29. }
  30.  
  31. void print(Node* head){
  32. while(head != NULL){
  33. cout<<head->data<<" ";
  34. head = head->next;
  35. }
  36. cout<<endl;
  37. }
  38.  
  39. void merge(Node*& h1, Node*& h2){
  40.  
  41. if(h1 == NULL){
  42. h1 = h2;
  43. return;
  44. }else if(h2 == NULL){
  45. h2 = h1;
  46. return;
  47. }
  48.  
  49. Node* t1 = h1;
  50. Node* t2 = h2;
  51. Node* ln = NULL;
  52. if(t1->data < t2->data){
  53. h1 = t1;
  54. h2 = t1;
  55. ln = t1;
  56. t1 = t1->next;
  57. }else{
  58. h1 = t2;
  59. h2 = t2;
  60. ln = t2;
  61. t2 = t2->next;
  62. }
  63.  
  64. while(t1!=NULL && t2!=NULL){
  65. if(t1->data < t2->data){
  66. ln->next = t1;
  67. ln = t1;
  68. t1 = t1->next;
  69. }else{
  70. ln->next = t2;
  71. ln = t2;
  72. t2 = t2->next;
  73. }
  74. }
  75.  
  76. while(t1!=NULL){
  77. ln->next = t1;
  78. ln = t1;
  79. t1 = t1->next;
  80. }
  81.  
  82. while(t2!=NULL){
  83. ln->next = t2;
  84. ln = t2;
  85. t2 = t2->next;
  86. }
  87.  
  88. }
  89.  
  90. int main() {
  91. int t;
  92. cin>>t;
  93. while(t){
  94. int n1;
  95. cin>>n1;
  96. Node* h1 = NULL;
  97. for(int i = 0; i < n1; i++){
  98. int temp;
  99. cin>>temp;
  100. insert(h1,temp);
  101. }
  102.  
  103. int n2;
  104. cin>>n2;
  105. Node* h2 = NULL;
  106. for(int i = 0; i < n2; i++){
  107. int temp;
  108. cin>>temp;
  109. insert(h2,temp);
  110. }
  111.  
  112. merge(h1,h2);
  113. print(h1);
  114.  
  115. t--;
  116. }
  117. return 0;
  118. }
Success #stdin #stdout 0s 4280KB
stdin
1
4
1 3 5 7
3
2 4 6
stdout
1 2 3 4 5 6 7