fork download
  1. #include<iostream>
  2. using namespace std;
  3. class node{
  4. public:
  5. node *next;
  6. long long int data;
  7. node(long long int d){
  8. next = NULL;
  9. data = d;
  10. }
  11. };
  12. void insertAtTail(node *&head, long long 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, long long 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. int length(node*head){
  39. int count=0;
  40. while(head!=NULL){
  41. head=head->next;
  42. count++;
  43. }
  44. return count;
  45. }
  46. void merge(node *a, node *b){
  47. int l1=length(a);
  48. int l2 = length(b);
  49. node *c=NULL;
  50. for(int i=0;i<(l1+l2);i++){
  51.  
  52. if(a==NULL)
  53. {
  54. c=b;
  55. b=b->next;
  56. c=c->next;
  57. }
  58. else if(b==NULL){
  59. c=a;
  60. a=a->next;
  61. c=c->next;
  62. }
  63.  
  64. if(a->data < b->data){
  65. c=a;
  66. a=a->next;
  67. c=c->next;
  68. }
  69. else{
  70. c=b;
  71. b=b->next;
  72. c=c->next;
  73. }
  74.  
  75. }
  76. while(c!=NULL){
  77. cout<<c<<" ";
  78. c=c->next;
  79. }
  80. }
  81.  
  82. int main(){
  83. node *head1 = NULL;
  84. node *head2 = NULL;
  85.  
  86. int t;
  87. long long int n1,n2;
  88. cin>>t;
  89.  
  90. for(int i=0;i<t;i++){
  91. cin>>n1;
  92. head1 = buildInput(head1,n1);
  93. cin>>n2;
  94. head2 = buildInput(head2,n2);
  95. merge(head1,head2);
  96.  
  97. }
  98.  
  99. return 0;
  100. }
Time limit exceeded #stdin #stdout 5s 5644KB
stdin
Standard input is empty
stdout
Standard output is empty