fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. typedef enum { FALSE, TRUE} bool;
  4.  
  5. typedef struct Bloc
  6. {
  7. int number;
  8. struct Bloc *next;
  9. } Bloc;
  10.  
  11. typedef Bloc *Liste ;
  12.  
  13. void initEmpty(Liste *L);
  14.  
  15. bool isEmpty(Liste l);
  16.  
  17. int value(Liste l);
  18.  
  19. Liste add(int x, Liste l);
  20.  
  21. void stack(int x, Liste* L);
  22. void print_iter(Liste l);
  23.  
  24.  
  25. void initEmpty( Liste *L)
  26. {
  27. *L = NULL ;
  28. }
  29.  
  30. bool isEmpty(Liste l)
  31. {
  32. return l == NULL ;
  33. }
  34.  
  35. int value(Liste l)
  36. {
  37. return l->number ;
  38. }
  39.  
  40. Liste add(int x, Liste l)
  41. {
  42. Liste tmp = (Liste) malloc(sizeof(Bloc)) ;
  43. tmp->number = x ;
  44. tmp->next = l ;
  45. return tmp ;
  46. }
  47.  
  48. void stack(int x, Liste *L)
  49. {
  50. *L = add(x,*L) ;
  51. }
  52.  
  53. Liste next(Liste l)
  54. {
  55. return l->next ;
  56. }
  57.  
  58. void print_iter(Liste l)
  59. {
  60. Liste L2 = l;
  61. while(!isEmpty(L2))
  62. {
  63. printf("%d ", value(L2));
  64. L2 = next(L2);
  65. }
  66. printf("\n");
  67. }
  68.  
  69. void BisAddBeforeLastZero(Liste *l, int x, Liste *lastOcc) {
  70. if (isEmpty(*l)) {
  71. if (*lastOcc != NULL) {
  72. stack(x, lastOcc);
  73. } else{
  74. // No zero, add to tail
  75. stack(x, l);
  76. }
  77. } else {
  78. if (value(*l) == 0) {
  79. lastOcc = l; // Zero has been found, get address
  80. }
  81. BisAddBeforeLastZero(&(*l)->next, x, lastOcc); // go through the end
  82. }
  83. }
  84.  
  85. void AddBeforeLastZero(Liste *L, int x) {
  86. Liste lastOcc = NULL;
  87. BisAddBeforeLastZero(L, x, &lastOcc);
  88. }
  89.  
  90. int main(void) {
  91. Liste l;
  92. initEmpty(&l);
  93.  
  94. stack(0, &l);
  95. stack(9, &l);
  96. stack(0, &l);
  97. stack(12, &l);
  98. printf("[with zero]:\n");
  99. print_iter(l);
  100. AddBeforeLastZero(&l, 50);
  101. print_iter(l);
  102. printf("\n"); return 0;
  103. }
  104.  
Success #stdin #stdout 0s 5392KB
stdin
Standard input is empty
stdout
[with zero]:
12 0 9 0 
12 0 9 50 0