Implement Stack Using Array with Push and Pop Operations

Code

#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#define MAX 10

void process_stack(int n) {
    // Your logic here
    char cmd[10];
    int stack[MAX];
    int run = -1;

    for(int i = 0; i < n; i++){
        scanf("%s", cmd);
        if(strncmp(cmd, "push",4) == 0){
            int num;
            scanf("%d", &num);
            if(run >= 9){
                printf("Stack Overflow\n");
                continue;
            }
            stack[++run] = num;
            // printf("%d\n", stack[run]);
        } 
        else{
            if(run < 0){
                printf("Stack Underflow\n");
                continue;
            }
            printf("%d\n", stack[run]);
            --run;
        }
        // printf("current buff :%d\n", stack[run]);
        
    }

}

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