Advertisement
Mary_99

task1.c

Oct 11th, 2019
275
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.32 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stdbool.h>
  4. #include "task1a.h"
  5.  
  6. Stack* init(int size)
  7. {
  8.     Stack*s = (Stack*)malloc(sizeof(Stack));
  9.     if(!s)// if malloc fails
  10.     {
  11.         printf(" Error -- Unalble to allocate memory , terminating the program\n");
  12.         abort();
  13.     }
  14.    
  15.     s->data = (int*)malloc(sizeof(int) * size); //allocation of the array for the stack
  16.    
  17.     if(!s->data)
  18.     {
  19.         printf(" Error -- Unalble to allocate memory , terminating the program\n");
  20.         abort();    
  21.     }
  22.    
  23.     s->top = -1;
  24.     s->size = size;
  25.     return s;
  26.    
  27. }
  28.  
  29.  
  30. void push(Stack *s, int element)
  31. {
  32.  
  33.    if(s->top == s->size -1)
  34.     {
  35.         s->data = realloc(s->data, s->size*2*sizeof(int));
  36.         if (!s->data)
  37.         {
  38.             free(s->data);
  39.             perror("realloc");
  40.         }
  41.         s->size *= 2;
  42.     }
  43.    
  44.     s->data[++s->top] = element;
  45. }
  46.  
  47.  
  48. int pop(Stack* s)
  49. {
  50.     if(isEmpty(s))
  51.     {
  52.         printf("Stack is empty");
  53.         abort();
  54.     }
  55.     else
  56.     {
  57.         return s->data[s->top--];
  58.     }
  59. }
  60.  
  61. bool isEmpty(Stack *s)
  62. {
  63.     if (s->top == -1)
  64.     {
  65.         return true;
  66.        
  67.     }
  68.     else
  69.     {
  70.         return false;
  71.        
  72.     }
  73. }
  74.  
  75.  
  76. void destroy (Stack *s)
  77. {
  78.     free(s->data);
  79.     free(s);
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement