Implementation of stack using ARRAY

amannarayanm · October 11, 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 *ptr,int element)
{
    ptr->top++;
    ptr->arr[ptr->top] = element;
}

int pop(struct stack *ptr)
{
    int element = ptr->arr[ptr->top];
    ptr->top--;
    return element;
}

int peak(struct stack *ptr,int position){
    return ptr->arr[ptr->top-position + 1];
}

int stackTop(struct stack *ptr){
    return ptr->arr[ptr->top];
}

int stackBottom(struct stack *ptr){
    return ptr->arr[0];
}

int main()
{
    struct stack *sp;
    sp = (struct stack*)malloc(sizeof(struct stack));
    
    sp->top = -1;
    sp->size = 5;
    sp->arr = (int *)malloc(sp->size*sizeof(int));
    
    // if(isEmpty(sp))
    // {
    //     printf("\nYour stack is Empty");
    // }
    // else
    // {
    //   printf("\nYour stack is not Empty");  
    // }
    // if(isFull(sp))
    // {
    //      printf("\nYour stack is Overflow");
    // }
    // else
    // {
    //      printf("\nYour stack is not Full");
    // }
    push(sp,45);
    push(sp,65);
    push(sp,12);
    push(sp,66);
    push(sp,98);
   
    // for Display the stack
    for(int i=1;i<=sp->size;i++){
        printf("Position %d : %d\n",i,peak(sp,i));
    }
    
    // Top and Bottom element
    printf("Top element : %d\n",stackTop(sp));
    printf("Bottom element : %d\n",stackBottom(sp));
    
    pop(sp);
    
     printf("Top element : %d\n",stackTop(sp));
    
    return 0;
}

Comments

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