Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <stdbool.h>
- #define SIZE 5
- typedef struct{
- int* data;
- int top;
- int size;
- } Stack;
- Stack* init(int size);
- void destroy(Stack* s);
- void push(Stack *s, int element);
- int pop(Stack* s);
- bool isEmpty(Stack* s);
- int main( int argc, char const *argv[])
- {
- Stack*s1 = init(SIZE);
- push(s1, 10);
- push(s1, 20);
- push(s1, 30);
- push(s1, 40);
- push(s1, 50);
- printf("Size of the stack: %d\n",s1->size);
- push(s1, 60);
- printf("Size of the stack: %d\n",s1->size);
- while(s1->top != -1)
- {
- printf("%d\n", pop(s1));
- }
- destroy (s1);
- return 0;
- }
- Stack* init(int size)
- {
- Stack*s = (Stack*)malloc(sizeof(Stack));
- if(!s)// if malloc fails
- {
- printf(" Error -- Unalble to allocate memory , terminating the program\n");
- abort();
- }
- s->data = (int*)malloc(sizeof(int) * size); //allocation of the array for the stack
- if(!s->data)
- {
- printf(" Error -- Unalble to allocate memory , terminating the program\n");
- abort();
- }
- s->top = -1;
- s->size = size;
- return s;
- }
- void push(Stack *s, int element)
- {
- if(s->top == s->size -1)
- {
- s->data = realloc(s->data, s->size*2*sizeof(int));
- if (!s->data)
- {
- free(s->data);
- perror("realloc");
- }
- s->size *= 2;
- }
- s->data[++s->top] = element;
- }
- int pop(Stack* s)
- {
- if(isEmpty(s))
- {
- printf("Stack is empty");
- abort();
- }
- else
- {
- return s->data[s->top--];
- }
- }
- bool isEmpty(Stack *s)
- {
- if (s->top == -1)
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- void destroy (Stack *s)
- {
- free(s->data);
- free(s);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement