Advertisement
Guest User

task2a

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