fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. /* http://p...content-available-to-author-only...a.org/wiki/Stos_(informatyka)#Lista */
  5.  
  6. typedef struct el {
  7. struct el *prev;
  8. int val;
  9. } el;
  10.  
  11. typedef struct {
  12. el *top;
  13. } lifo;
  14.  
  15. lifo *lifo_init(void) {
  16. lifo *l = malloc(sizeof(lifo));
  17. l->top = NULL;
  18. return l;
  19. }
  20.  
  21. void lifo_push(lifo *l, int num) {
  22. el *new = malloc(sizeof(el));
  23. new->val = num;
  24. new->prev = l->top;
  25. l->top = new;
  26. }
  27.  
  28. int lifo_pop(lifo *l) {
  29. el *tofree = l->top;
  30. int ret = tofree->val;
  31. l->top = tofree->prev;
  32. free(tofree);
  33. return ret;
  34. }
  35.  
  36. void lifo_show(const lifo *l) {
  37. el *next = l->top;
  38. while(next) {
  39. printf("%d\n",next->val);
  40. next = next->prev;
  41. }
  42. }
  43.  
  44. void lifo_clean(lifo *l) {
  45. el *next, *tofree = l->top;
  46. while(tofree) {
  47. next = tofree->prev;
  48. free(tofree);
  49. tofree = next;
  50. }
  51. l->top = NULL;
  52. }
  53.  
  54. void lifo_free(lifo *l) {
  55. if(!l) return;
  56. lifo_clean(l);
  57. free(l);
  58. }
  59.  
  60. #define IDEONE
  61. int userinput(void) {
  62. #ifndef IDEONE
  63. printf("[1] Dodaj element\n");
  64. printf("[2] Zdejmij element\n");
  65. printf("[3] Wyswietl stos\n");
  66. printf("[4] Wyczysc stos\n");
  67. printf("[5] Usun stos\n");
  68. printf("[0] Wyjście z programu\n");
  69. #endif IDEONE
  70. int input;
  71. scanf("%d",&input);
  72. return input;
  73. }
  74.  
  75. int main(void) {
  76. lifo *l = lifo_init();
  77. int choice = -1;
  78. while((choice = userinput())) {
  79. switch(choice) {
  80. int num;
  81. case 1:
  82. scanf("%d",&num);
  83. lifo_push(l,num);
  84. break;
  85. case 2:
  86. printf("Zdjeto: %d\n",lifo_pop(l));
  87. break;
  88. case 3:
  89. lifo_show(l);
  90. break;
  91. case 4:
  92. lifo_clean(l);
  93. break;
  94. case 5:
  95. lifo_free(l);
  96. l = NULL; /* bez wiszacych wskaznikow */
  97. break;
  98. }
  99. }
  100. /* zwalnanie pamieci */
  101. lifo_free(l);
  102. return 0;
  103. }
  104.  
Success #stdin #stdout 0s 2384KB
stdin
3
1 111
1 222
1 333
1 444
3
2
2
1 888
3
4
1 12345
1 56789
3
4
3
1 14141
5
0
stdout
444
333
222
111
Zdjeto: 444
Zdjeto: 333
888
222
111
56789
12345