STACK IMPLEMENTATION

amannarayanm · October 09, 2021 · C
#include <stdio.h>
#include <stdlib.h>

struct stack{
  int top;
  int size;
  int *arr;
};

int isFull(struct stack *ptr)
{
    if(ptr->top == ptr->size-1)
    {
        return 1;
    }
    return 0;
}

int isEmpty(struct stack*ptr)
{
    if(ptr->top == -1)
    {
        return 1;
    }
    return 0;
}

void push(struct stack *sp,int element)
{
    if(isFull(sp)){
        printf("Your stack is overFlow");
    }
    else
    {
        sp->top++;
        sp->arr[sp->top] = element;
    }
}

int pop(struct stack *sp)
{
    if(isEmpty(sp)){
        printf("Your stack is underFlow");
    }
    else{
        int element = sp->arr[sp->top];
        sp->top--;
        return element;
    }
}

int main() {
    
    struct stack *sp = (struct stack *)malloc(sizeof(struct stack ));
    sp->top = -1;
    sp->size = 10;
    sp->arr = (int *)malloc(sp->size*sizeof(int));
    
    if(isEmpty(sp)){
        printf("Your stack is underFlow");
    }
    push(sp,45);
    push(sp,87);
    if(isEmpty(sp)){
        printf("\nYour stack is underFlow");
    }
    else
    {
        printf("\nYour stack is not underFlow");
    }
    pop(sp);
    pop(sp);
     if(isEmpty(sp)){
        printf("\nYour stack is underFlow");
    }
    else
    {
        printf("\nYour stack is not underFlow");
    }
    
    
    return 0;
}

Comments

Please sign up or log in to contribute to the discussion.