Munashedov

stack

Nov 23rd, 2021 (edited)
226
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.40 KB | None | 0 0
  1. struct Stack{
  2.     int count;
  3.     int capacity;
  4.     int *elements;
  5. };
  6.  
  7. struct Stack StackCreate(void){
  8.     struct Stack s = {
  9.         .count = 0,
  10.         .capacity = 0,
  11.         .elements = 0
  12.     };
  13.     return s;
  14. }
  15.  
  16. void StackExpand(struct Stack *s){
  17.     if(s->capacity == 0) {
  18.         s->capacity++;
  19.     }
  20.     s->capacity *= 2;
  21.     int *temp = realloc(s->elements, sizeof(s->elements[0]) * s->capacity);
  22.     if(temp == NULL){
  23.         fprintf(stderr, "Realloc failed to expand stack.\n");
  24.         exit(1);
  25.     } else {
  26.         s->elements = temp;
  27.     }
  28. }
  29.  
  30. void StackShrink(struct Stack *s){
  31.     s->capacity = (int)(s->capacity / 1.5f);
  32.     int *temp = realloc(s->elements, sizeof(s->elements[0]) * s->capacity);
  33.     if(temp == NULL){
  34.         fprintf(stderr, "Realloc failed to shrink stack.\n");
  35.         exit(1);
  36.     } else {
  37.         s->elements = temp;
  38.     }
  39. }
  40.  
  41. void StackPush(struct Stack *s, int input){
  42.     if(s->count == s->capacity){
  43.         StackExpand(s);
  44.     }
  45.     s->elements[s->count++] = input;
  46. }
  47.  
  48. int StackPop(struct Stack *s){
  49.     if(s->capacity >= s->count * 2.5f) {
  50.         StackShrink(s);
  51.     }
  52.     if(s->count > 1){
  53.         s->count--;
  54.         return (s->elements[s->count]);
  55.     } else {
  56.         fprintf(stderr, "Popped empty stack.\n");
  57.         return 0;
  58.     }
  59. }
  60.  
  61. void StackPrint(struct Stack *s){
  62.     printf("[");
  63.     for(int i = 0; i < s->count; ++i){
  64.         printf("%X", s->elements[i]);
  65.         if(i < s->count-1){
  66.             printf(",");
  67.         }
  68.     }
  69.     printf("]\n");
  70.     printf("Count:    %i\n", s->count);
  71.     printf("Capacity: %i\n", s->capacity);
  72. }
Add Comment
Please, Sign In to add comment