fork download
  1. #include <stdio.h>
  2.  
  3. typedef struct node
  4. {
  5. struct node* next;
  6. int data;
  7. } Node;
  8.  
  9. Node * Change_Even_Odd(Node * L)
  10. {
  11. Node *oddhead = NULL, *evenhead = NULL, *lastodd = NULL, *lasteven = NULL, *current = L;
  12. while (current != NULL)
  13. {
  14. // if current is even node
  15. if (current->data % 2 == 0)
  16. {
  17. if (evenhead == NULL)
  18. {
  19. evenhead = current;
  20. lasteven = current;
  21. }
  22. else
  23. {
  24. lasteven->next = current; // to connect the node to the list in the end
  25. lasteven = current; // final list
  26. }
  27. }
  28. else
  29. {
  30. // if current is odd node
  31. if (oddhead == NULL)
  32. {
  33. oddhead = current;
  34. lastodd = current;
  35. }
  36. else
  37. {
  38. lastodd->next = current;
  39. lastodd = current;
  40. }
  41.  
  42. }
  43. current = current->next;
  44. }
  45.  
  46. if (evenhead != NULL)
  47. L = evenhead;
  48. if (lasteven != NULL)
  49. lasteven->next = oddhead;
  50. if (lastodd != NULL)
  51. lastodd->next = NULL;
  52.  
  53. return L;
  54.  
  55. }
  56.  
  57. void p(Node* L)
  58. {
  59. while(L)
  60. {
  61. printf("%d, ", L->data);
  62. L = L->next;
  63. }
  64. printf("\n");
  65. }
  66.  
  67. void f(Node* L)
  68. {
  69. Node*tmp;
  70. while(L)
  71. {
  72. tmp = L;
  73. L = L->next;
  74. free(tmp);
  75. }
  76. }
  77.  
  78. int main(void) {
  79. int a[] = {3,1,8,2,5,6};
  80. Node* L;
  81. L = malloc(sizeof *L); // Add check for NULL
  82. Node* tmp = L;
  83. int i = 0;
  84. while(1)
  85. {
  86. tmp->data = a[i];
  87. tmp->next = NULL;
  88. ++i;
  89. if (i == (sizeof a)/(sizeof(int))) break;
  90. tmp->next = malloc(sizeof *L); // Add check for NULL
  91. tmp = tmp->next;
  92. }
  93.  
  94. p(L);
  95. L = Change_Even_Odd(L);
  96. p(L);
  97.  
  98. f(L);
  99.  
  100. return 0;
  101. }
  102.  
Success #stdin #stdout 0s 2300KB
stdin
Standard input is empty
stdout
3, 1, 8, 2, 5, 6, 
8, 2, 6, 3, 1, 5,