fork(1) download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. struct NodeFifo
  6. {
  7. char *value;
  8. struct NodeFifo *next;
  9. };
  10.  
  11. struct Fifo
  12. {
  13. struct NodeFifo *head,*tail;
  14. };
  15.  
  16. struct Fifo init()
  17. {
  18. struct Fifo f={NULL,NULL};
  19. return f;
  20. }
  21.  
  22. struct NodeFifo *newNode(const char *value,struct NodeFifo *next)
  23. {
  24. struct NodeFifo *add;
  25. add=(struct NodeFifo*)malloc(sizeof(struct NodeFifo));
  26. add->value=strdup(value);
  27. add->next=next;
  28. return add;
  29. }
  30.  
  31. void addValue(struct Fifo *f,const char *value)
  32. {
  33. struct NodeFifo *add;
  34. add=newNode(value,NULL);
  35. if(f->tail) f->tail->next=add;
  36. else f->head=add;
  37. f->tail=add;
  38. }
  39.  
  40. void pushValue(struct Fifo *f,const char *value)
  41. {
  42. f->head=newNode(value,f->head);
  43. if(!f->tail) f->tail=f->head;
  44. }
  45.  
  46. void print(struct Fifo *f)
  47. {
  48. struct NodeFifo *i;
  49. printf("[");
  50. for(i=f->head;i;i=i->next)
  51. {
  52. if(i!=f->head) printf(", ");
  53. printf("%s",i->value);
  54. }
  55. printf(" ]\n");
  56. }
  57.  
  58. const char *head(struct Fifo *f)
  59. {
  60. return f->head?f->head->value:NULL;
  61. }
  62.  
  63. const char *tail(struct Fifo *f)
  64. {
  65. return f->tail?f->tail->value:NULL;
  66. }
  67.  
  68. void popValue(struct Fifo *f)
  69. {
  70. struct NodeFifo *tmp;
  71. if(f->head)
  72. {
  73. tmp=f->head;
  74. f->head=tmp->next;
  75. if(!f->head) f->tail=NULL;
  76. free(tmp->value);
  77. free(tmp);
  78. }
  79. }
  80.  
  81.  
  82. void reverse(struct Fifo *f)
  83. {
  84. struct NodeFifo *tmp,*next;
  85. tmp=f->head;
  86. f->head=f->tail=NULL;
  87. while(tmp)
  88. {
  89. next=tmp->next;
  90. tmp->next=f->head;
  91. f->head=tmp;
  92. if(!f->tail) f->tail=tmp;
  93. tmp=next;
  94. }
  95. }
  96.  
  97. void deinit(struct Fifo *f)
  98. {
  99. while(f->head)
  100. {
  101. f->tail=f->head;
  102. f->head=f->head->next;
  103. free(f->tail->value);
  104. free(f->tail);
  105. }
  106. f->tail=NULL;
  107. }
  108.  
  109. int main()
  110. {
  111. struct Fifo f=init();
  112.  
  113. addValue(&f,"jeden");
  114. addValue(&f,"dwa");
  115. addValue(&f,"trzy");
  116. addValue(&f,"cztery");
  117.  
  118. print(&f);
  119. reverse(&f);
  120. print(&f);
  121. reverse(&f);
  122. print(&f);
  123.  
  124. printf("%s\n",head(&f)); popValue(&f);
  125. print(&f);
  126. printf("%s\n",head(&f)); popValue(&f);
  127. print(&f);
  128.  
  129. deinit(&f);
  130. return 0;
  131. }
Success #stdin #stdout 0s 2380KB
stdin
Standard input is empty
stdout
[jeden, dwa, trzy, cztery ]
[cztery, trzy, dwa, jeden ]
[jeden, dwa, trzy, cztery ]
jeden
[dwa, trzy, cztery ]
dwa
[trzy, cztery ]