fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. struct node{
  4. int data;
  5. node* next;
  6. node(int value)
  7. {
  8. data=value;
  9. next=nullptr;
  10. }
  11. };
  12. bool isprime(int num)
  13. {
  14. if(num==1) return false;
  15. int a=0;
  16. for(int i=2;i*i<=num;i++)
  17. {
  18. if(num%i==0) a++;
  19. }
  20. if(!a) return true;
  21. else return false;
  22. }
  23. class linkedlist{
  24. public:
  25. node* head;
  26. linkedlist(){
  27. head=nullptr;
  28. }
  29.  
  30. void add(int val)
  31. {
  32. node* newnode=new node(val);
  33. if(!head)
  34. {
  35. head=newnode;
  36. newnode->next=nullptr;
  37. return;
  38. }
  39. node* temp=head;
  40. while(temp->next!=nullptr)
  41. {
  42. temp=temp->next;
  43. }
  44. temp->next=newnode;
  45. newnode->next=nullptr;
  46. }
  47. void display()
  48. {
  49. node* temp=head;
  50. while(temp!=nullptr)
  51. {
  52. cout<<temp->data<<" ";
  53. temp=temp->next;
  54. }
  55. }
  56.  
  57. };
  58. void insert(linkedlist &l1,linkedlist &l2)
  59. {
  60. node* curra=l1.head;
  61. node* currb=l2.head;
  62. node* preva=nullptr;
  63. int pos=1;
  64. while(curra!=nullptr && currb!=nullptr)
  65. {
  66. if(isprime(pos))
  67. {
  68. node* save=currb->next;
  69. currb->next=curra;
  70. preva->next=currb;
  71. preva=currb;
  72. currb=save;
  73.  
  74. }
  75. else
  76. {preva=curra;curra=curra->next;}
  77. pos++;
  78. }
  79.  
  80. }
  81. int main()
  82. {
  83. int len1,len2;
  84. cin>>len1>>len2;
  85. linkedlist l1,l2;
  86. for(int i=0;i<len1;i++)
  87. {
  88. int m;cin>>m;
  89. l1.add(m);
  90. }
  91. for(int i=0;i<len2;i++)
  92. {
  93. int m;cin>>m;
  94. l2.add(m);
  95. }
  96. cout<<endl;
  97. l1.display();cout<<endl;
  98. l2.display();cout<<endl;
  99. insert(l1,l2);
  100. l1.display();
  101. return 0;
  102. }
Success #stdin #stdout 0s 5316KB
stdin
5 3 
10 20 30 40 50 
1 2 3
stdout
10 20 30 40 50 
1 2 3 
10 1 2 20 3 30 40 50