Advertisement
Mary_99

push

Oct 11th, 2019
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.00 KB | None | 0 0
  1. void push(Stack *s, int element)
  2. {
  3.     //cheak if array is overflowed or not
  4.     //if aary is overflowed we need to double the size of the array
  5.     if(s->top == s->size -1)// is overflowed
  6.     {
  7.         //double the size of the array
  8.         int *temp = (int*)malloc(sizeof(int)* s->size * 2);
  9.         if (temp == '\0') // we can not alocate no more space there
  10.         {
  11.             printf("Error -- Unalble to allocate memory... ");
  12.             return;
  13.         }
  14.         //memory allocated succesfully
  15.         int i = 0;
  16.         for(i = 0; i <= s->top; ++i)// copying existing data to the data array on the new allocated array
  17.         {
  18.             temp[i] = s->data[i];
  19.         }
  20.         free(s->data);
  21.         s->data = temp;
  22.         s->size *= 2;
  23.     }
  24.     // if not ovcerflowed
  25.     //top willl be increment by 1 fist and than that top will be index
  26.     s->data[++s->top] = element; //this is the push operation incres the top by 1 and than put the value at the top index of the array    
  27. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement