Implement Stack Using Array with Push and Pop Operations

Code

#include <stdio.h>
#include <stdint.h>
#include <string.h>

#define MAX 10
typedef struct  {
    int arr[MAX];
    int tail = 0; 
    int head = 0; 
    int count = 0;
    

}stack;

void process_stack(int n) {
    // Your logic here
    char operation_1[10] = "push";
    char operation_2[10] = "pop";
    stack res;
    stack *ptr;
    ptr = &res;

    for (int i=0 ; i < n ; i ++)
    {
        char operation[10]; 
        int value; 
        
        scanf("%s ",&operation);
        if (strcmp(operation_1 ,operation) == 0)
        {
            scanf("%d" , &value);
            //printf("%d \n"  , ptr->head);
             // push 
             if (ptr->head >= MAX)
             {
                printf("Stack Overflow\n");
             }
             else 
             {

                    ptr->arr[ptr->head] = value;
                    ptr->tail = ptr->head;
                    ptr->head ++;
                    ptr->count ++;
                   
             }
           
           

           


        }
        else if (strcmp(operation_2,operation) == 0)
        {
            //printf("%s \n" , operation );
            // check if arr is empty or no :- 

            if (ptr->tail <= 0 && ptr->count == 0)
             {
                printf("Stack Underflow\n");
             }
             else 
             {

                
                printf("%d\n" , ptr->arr[ptr->tail]);
                ptr->tail --;
                ptr->count --;
             }
           


        }
        

       
    }
   
}

int main() {
    int n;
    scanf("%d", &n);
    getchar(); // Consume newline after number

    process_stack(n);
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

5 push 10 push 20 pop pop pop

Expected Output

20 10 Stack Underflow