Advertisement
Mary_99

TASK1a do oddania

Oct 11th, 2019
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.92 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stdbool.h>
  4.  
  5. #define SIZE 5
  6.  
  7. typedef struct{
  8.  
  9.     int* data;
  10.     int top;
  11.     int size;
  12. } Stack;
  13.  
  14.  
  15. Stack* init(int size);
  16. void destroy(Stack* s);
  17. void push(Stack *s, int element);
  18. int pop(Stack* s);
  19. bool isEmpty(Stack* s);
  20.  
  21.  
  22. int main( int argc, char const *argv[])
  23. {
  24.     Stack*s1 = init(SIZE);
  25.     push(s1, 10);
  26.     push(s1, 20);
  27.     push(s1, 30);
  28.     push(s1, 40);
  29.     push(s1, 50);
  30.     printf("Size of the stack: %d\n",s1->size);
  31.     push(s1, 60);
  32.     printf("Size of the stack: %d\n",s1->size);
  33.    
  34.     while(s1->top != -1)
  35.     {
  36.         printf("%d\n", pop(s1));
  37.     }
  38.    
  39.     destroy (s1);
  40.     return 0;
  41.    
  42. }
  43.  
  44.  
  45. Stack* init(int size)
  46. {
  47.     Stack*s = (Stack*)malloc(sizeof(Stack));
  48.     if(!s)// if malloc fails
  49.     {
  50.         printf(" Error -- Unalble to allocate memory , terminating the program\n");
  51.         abort();
  52.     }
  53.    
  54.     s->data = (int*)malloc(sizeof(int) * size); //allocation of the array for the stack
  55.    
  56.     if(!s->data)
  57.     {
  58.         printf(" Error -- Unalble to allocate memory , terminating the program\n");
  59.         abort();    
  60.     }
  61.    
  62.     s->top = -1;
  63.     s->size = size;
  64.     return s;
  65.    
  66. }
  67.  
  68.  
  69. void push(Stack *s, int element)
  70. {
  71.  
  72.    if(s->top == s->size -1)
  73.     {
  74.         s->data = realloc(s->data, s->size*2*sizeof(int));
  75.         if (!s->data)
  76.         {
  77.             free(s->data);
  78.             perror("realloc");
  79.         }
  80.         s->size *= 2;
  81.     }
  82.    
  83.     s->data[++s->top] = element;
  84. }
  85.  
  86.  
  87. int pop(Stack* s)
  88. {
  89.     if(isEmpty(s))
  90.     {
  91.         printf("Stack is empty");
  92.         abort();
  93.     }
  94.     else
  95.     {
  96.         return s->data[s->top--];
  97.     }
  98. }
  99.  
  100. bool isEmpty(Stack *s)
  101. {
  102.     if (s->top == -1)
  103.     {
  104.         return true;
  105.        
  106.     }
  107.     else
  108.     {
  109.         return false;
  110.        
  111.     }
  112. }
  113.  
  114.  
  115. void destroy (Stack *s)
  116. {
  117.     free(s->data);
  118.     free(s);
  119. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement