stack.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. typedef struct stack {
  4. int *data;
  5. int ptr;
  6. int size;
  7. } STACK;
  8. STACK *init(int size)
  9. {
  10. STACK *stack = malloc(sizeof(STACK));
  11. stack->ptr = 0;
  12. stack->size = size;
  13. stack->data = (int *) calloc(size, sizeof(int));
  14. return stack;
  15. }
  16. void push(STACK *stack, int val)
  17. {
  18. if(stack->ptr >= stack->size) {
  19. stack->size = stack->size * 3 / 2;
  20. stack->data = (int *) realloc(stack->data, stack->size * sizeof(*stack->data));
  21. }
  22. stack->data[stack->ptr++] = val;
  23. }
  24. void pop(STACK *stack)
  25. {
  26. if(stack->size > stack->ptr*2) {
  27. stack->size = stack->size/2;
  28. stack->data = realloc(stack->data, stack->size * sizeof(*stack->data));
  29. }
  30. stack->ptr--;
  31. }
  32. void print(STACK *stack)
  33. {
  34. int counter = 0;
  35. while(counter < stack->ptr) {
  36. printf("%d ", stack->data[counter++]);
  37. }
  38. printf("\n");
  39. }
  40. int main()
  41. {
  42. STACK *stack = init(5);
  43. printf("Size: %d\n", stack->size);
  44. printf("Actual size: %lu\n", sizeof(stack->data)/sizeof(stack->data[0]));
  45. push(stack, 12);
  46. push(stack, 2);
  47. push(stack, 22);
  48. print(stack);
  49. push(stack, 23);
  50. push(stack, 7);
  51. push(stack, 11);
  52. print(stack);
  53. pop(stack);
  54. print(stack);
  55. pop(stack);
  56. pop(stack);
  57. pop(stack);
  58. print(stack);
  59. printf("Size: %d\n", stack->size);
  60. printf("Actual size: %lu\n", sizeof(stack->data)/sizeof(stack->data[0]));
  61. return 0;
  62. }