push, pop, peek in stack

PHOTO EMBED

Wed Jun 22 2022 15:06:20 GMT+0000 (Coordinated Universal Time)

Saved by @KanishqJ8

#include <stdio.h>
#include <stdlib.h>
 
 struct stack{
     int size;
     int top;
     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 val){
     if(isFull(ptr)){
         printf("stack overflow");
     }
     else{
         ptr->top++;
         ptr->arr[ptr->top] = val;
     }
 }
 
 int pop(struct stack *ptr){
     if(isEmpty(ptr)){
         printf("stack underflow");
     }
     else{
         int val = ptr->arr[ptr->top];
         ptr->top--;
         return val;
     }
 }
 
 int peek(struct stack* sp,int i){
    if(sp->top-i+1<0){
        printf("invalid position\n");
        return -1;
    }
    return sp->arr[sp->top-i+1];
}
 
 int main(){
     struct stack *sp = (struct stack *)malloc (sizeof(struct stack));
     sp->size=10;
     sp->top=-1;
     sp->arr=(int*)malloc(sp->size * sizeof(int));
     printf("stack is successfully created ");
      printf("Before pushing, Full: %d\n", isFull(sp));
    printf("Before pushing, Empty: %d\n", isEmpty(sp));
     
    push(sp, 1);
    push(sp, 23);
    push(sp, 99);
    push(sp, 75);
    push(sp, 3);
    push(sp, 64);
    push(sp, 57);
    push(sp, 46);
    push(sp, 89);
    push(sp, 6); // ---> Pushed 10 values 
    // push(sp, 46); // Stack Overflow since the size of the stack is 10
    printf("After pushing, Full: %d\n", isFull(sp));
    printf("After pushing, Empty: %d\n", isEmpty(sp));
    printf("Popped %d from the stack\n", pop(sp)); // --> Last in first out!
    printf("Popped %d from the stack\n", pop(sp)); // --> Last in first out!
    printf("Popped %d from the stack\n", pop(sp)); // --> Last in first out!
    
    for(int j=1; j<= sp->top+1; j++){
        printf("positon %d : %d\n",j,peek(sp,j));
    }
     return 0;
 }
content_copyCOPY