fork download
  1. /*
  2.   Every even comes after the odd ones
  3.   Recursion Solutions
  4.   One test Case Fails
  5. */
  6.  
  7. #include<iostream>
  8. using namespace std;
  9. class node {
  10. public :
  11. int data;
  12. node *next;
  13.  
  14.  
  15. node(int d) {
  16. data = d;
  17. next = NULL;
  18. }
  19. };
  20.  
  21.  
  22. void insertAtTails(node *&head, int data) {
  23. if (head == NULL) {
  24. // insert at head
  25. head = new node(data);
  26. return;
  27. }
  28.  
  29. node *temp = head;
  30. while (temp->next != NULL) {
  31. temp = temp->next;
  32. }
  33.  
  34. // insert at head
  35. temp->next = new node(data);
  36.  
  37. }
  38.  
  39. void builtInInput(node *&head, int n) {
  40.  
  41. for (int i = 0; i < n; ++i)
  42. {
  43. int data;
  44. cin >> data;
  45. insertAtTails(head, data);
  46. }
  47. }
  48.  
  49. // Even-After-Odd problem
  50. node * evenAfterOdd(node *&head) {
  51.  
  52. //Base case if one or zero node
  53. if(head == NULL || head->next == NULL) {
  54. return head;
  55. }
  56.  
  57. // Recursive Case
  58. node *small_head = evenAfterOdd(head->next);
  59.  
  60. // First node is even and second is odd then replace it
  61. if(head->data%2 == 0 && small_head->data%2 != 0) {
  62. int head_data = head->data;
  63. int small_data = small_head->data;
  64. head->data = small_data;
  65. small_head->data = head_data;
  66.  
  67. }
  68. // head will point to next node
  69. head->next = small_head;
  70.  
  71. return head;
  72. }
  73.  
  74. // Find the elements are going to have to even and odd
  75.  
  76. void printLL(node *head) {
  77. while (head != NULL) {
  78. cout << head->data << " ";
  79. head = head->next;
  80. }
  81. }
  82.  
  83.  
  84. int main() {
  85. node * head = NULL;
  86. builtInInput(head , 5);
  87. node* result_head = evenAfterOdd(head);
  88. printLL(result_head);
  89. return 0;
  90. }
Success #stdin #stdout 0s 4492KB
stdin
Standard input is empty
stdout
0 0 0 0 0