Advertisement
Iamnotagenius

Untitled

Oct 9th, 2021
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.57 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. const int STACK_MIN_SIZE = 1024;
  6.  
  7. typedef struct {
  8.     int length;
  9.     int index;
  10.     void *buffer;
  11.     size_t size;
  12. } stack;
  13.  
  14. stack *create_stack(size_t size) {
  15.     stack *new = malloc(sizeof(stack));
  16.     new->length = STACK_MIN_SIZE;
  17.     new->index = -1;
  18.     new->buffer = malloc(size * new->length);
  19.     new->size = size;
  20.     return new;
  21. }
  22.  
  23. void delete_stack(stack *s) {
  24.     free(s->buffer);
  25.     free(s);
  26. }
  27.  
  28. void expand(stack *s) {
  29.     s->length *= 2;
  30.     s->buffer = realloc(s->buffer, s->length);
  31.     if (!s->buffer) {
  32.         fprintf(stderr, "Reallocating memory failed\n");
  33.         exit(1);
  34.     }
  35. }
  36.  
  37. void push(stack *s, void *element) {
  38.     if (s->length <= ++s->index)
  39.         expand(s);
  40.  
  41.     memcpy(s->buffer + s->index * s->size, element, s->size);
  42. }
  43.  
  44. int pop(stack *s, void *buf) {
  45.     if (s->index < 0)
  46.         return 0;
  47.  
  48.     memcpy(buf, s->buffer + s->index * s->size, s->size);
  49.     s->index--;
  50.     return 1;
  51. }
  52.  
  53. const char IN_FILE[] = "stack.in";
  54. const char OUT_FILE[] = "stack.out";
  55.  
  56. int main() {
  57.     stack *ints = create_stack(sizeof(int));
  58.     FILE *in = fopen(IN_FILE, "r"),
  59.          *out = fopen(OUT_FILE, "w");
  60.     /* this works though
  61.     stack *ints = malloc(sizeof(stack));
  62.     ints->buffer = malloc(100000 * sizeof(int));
  63.     ints->index = -1;
  64.     ints->length = 100000;
  65.     ints->size = sizeof(int); */
  66.     int n, x;
  67.     char op;
  68.     fscanf(in, "%d", &n);
  69.     for (int i = 0; i < n; ++i) {
  70.         fscanf(in, "\n%c", &op);
  71.         switch(op) {
  72.             case '+':
  73.                 fscanf(in, "%d", &x);
  74.                 push(ints, &x);
  75.                 break;
  76.             case '-':
  77.                 pop(ints, &x);
  78.                 fprintf(out, "%d\n", x);
  79.         }
  80.     }
  81. }
  82.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement