fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. class Node{
  5. public:
  6. int data;
  7. Node* next;
  8.  
  9. Node(int d){
  10. data = d;
  11. next = NULL;
  12. }
  13. };
  14.  
  15. void insert(Node*& head, int data){
  16.  
  17. if(head == NULL){
  18. head = new Node(data);
  19. return;
  20. }
  21.  
  22. Node* temp = head;
  23. while(temp->next != NULL){
  24. temp = temp->next;
  25. }
  26. temp->next = new Node(data);
  27.  
  28. }
  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 evenAfterOdd(Node*& head){
  40. // To check the approach I took just read the comments at the end of the prog
  41.  
  42. Node* evenLast = NULL, *evenFirst = NULL, *oddLast = NULL;
  43.  
  44. Node* temp = head;
  45.  
  46. while(temp!=NULL){
  47.  
  48. if(temp->data%2 == 0){
  49. if(evenFirst == NULL){
  50. evenFirst = temp;
  51. evenLast = temp;
  52. }else{
  53. evenLast->next = temp;
  54. evenLast = temp;
  55. }
  56. }else{
  57. if(oddLast == NULL){
  58. head = temp;
  59. oddLast = temp;
  60. }else{
  61. oddLast->next = temp;
  62. oddLast = temp;
  63. }
  64. }
  65. temp = temp->next;
  66. }
  67.  
  68. oddLast->next = evenFirst;
  69. evenLast->next = NULL;
  70. }
  71.  
  72. int main() {
  73. Node* head = NULL;
  74. int n;
  75. cin>>n;
  76. for(int i = 0; i < n; i++){
  77. int temp;
  78. cin>>temp;
  79. insert(head,temp);
  80. }
  81. evenAfterOdd(head);
  82. print(head);
  83. return 0;
  84. }
  85.  
  86.  
  87. // Instead of the above approach I will take 2 node pointers
  88. // One of them represents the last even node encountered and odd resp
  89. // We will also store the first of the Even list as we will do
  90. // oddLast->next = evenFirst
Success #stdin #stdout 0s 4380KB
stdin
5
1 2 2 2 1
stdout
1 1 2 2 2