Advertisement
Guest User

Untitled

a guest
Oct 17th, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.71 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. #ifndef DEBUG
  6. #define DEBUG(...) printf(__VA_ARGS__)
  7. #endif
  8.  
  9. #define SIZE 3
  10. #define GROW_BY 3
  11.  
  12.  
  13. struct stack_s {
  14. int *array;
  15. int top;
  16. int size;
  17. int is_dynamic;
  18. } stack_init = { .array=NULL, .top=-1, .size=0, .is_dynamic=0 };
  19. typedef struct stack_s stack_t;
  20.  
  21. int push(stack_t *stack, int val) {
  22. int retval = 0;
  23. //ako je stack pun
  24. if (stack->top == stack->size - 1) {
  25. //ako je stack dinamican
  26. if (stack->is_dynamic) {
  27. stack->array = (int *) realloc(stack->array, sizeof(int) * (stack->size + GROW_BY));
  28.  
  29. //ako ne uspijemo alocirati dodatni prostor
  30. if (!(stack->array)) {
  31. return -1;
  32. }
  33.  
  34. stack->size += GROW_BY;
  35.  
  36. retval = 1;
  37. } else {
  38. return -1;
  39. }
  40. }
  41.  
  42. stack->top++;
  43. stack->array[stack->top] = val;
  44.  
  45. return retval;
  46. }
  47.  
  48. int pop(stack_t *stack) {
  49. //ako je stack prazan
  50. if(stack->top == -1) {
  51. return -1;
  52. }
  53.  
  54. stack->top--;
  55.  
  56. return 0;
  57. }
  58.  
  59. void print(stack_t stack) {
  60. printf("Stog: ");
  61.  
  62. for (int i = 0; i <= stack.top; i++) {
  63. printf("%d ", stack.array[i]);
  64. }
  65.  
  66. printf("\n");
  67. }
  68.  
  69. int main() {
  70. char menu_choice, is_dynamic_choice;
  71. stack_t stack = stack_init;
  72. int val, retval;
  73.  
  74. do {
  75. printf("Zelite li polje u kojem se implementira stog uciniti dinamickim? (Y/N): ");
  76. scanf(" %c", &is_dynamic_choice);
  77. } while (is_dynamic_choice!='Y' && is_dynamic_choice!='N');
  78. stack.is_dynamic = is_dynamic_choice=='Y';
  79.  
  80. // Ovdje alocirati memorijski prostor za polje i postaviti velicinu stoga
  81. stack.array = (int *) malloc (sizeof(int) * SIZE);
  82. stack.size = SIZE;
  83.  
  84. //DEBUG("\n(d) dodaj - push\n(b) brisi - pop\n(i) ispis - print\n(e) Exit\n");
  85. do {
  86. scanf(" %c", &menu_choice);
  87. switch (menu_choice) {
  88. case 'd':
  89. scanf("%d", &val);
  90. retval = push(&stack, val);
  91. if (retval==1) {
  92. printf("Stog je pun. Alocirao sam dodatni prostor.\n");
  93. } else if (retval==-1) {
  94. printf("Stog je pun. Ne mogu dodati element.\n");
  95. }
  96. break;
  97. case 'b':
  98. retval = pop(&stack);
  99. if (retval==-1) {
  100. printf("Stog je prazan. Ne mogu obrisati element.\n");
  101. }
  102. break;
  103. case 'i':
  104. print(stack);
  105. break;
  106. }
  107. } while (menu_choice!='e');
  108. free(stack.array);
  109. return 0;
  110. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement