Advertisement
Mary_99

2a + assert

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