88. Implement Stack Using Array with Push and Pop Operations

Back To All Submissions
Previous Submission
Next Submission

Code

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

#define MAX       10

void process_stack(int n) {
    int stack[MAX] = {0};
    int top = 0;

    while (n--) {
        char op[10] = {0};
        scanf("%s", op); 

        if (strcmp(op, "push") == 0) {
            int val;
            scanf("%d", &val); 

            if (top >= MAX) {
                printf("Stack Overflow\n");
            } else {
                stack[top] = val; 
                top++; 
            }
        } 
        else if (strcmp(op, "pop") == 0) {
            if (top <= 0) {
                printf("Stack Underflow\n");
            } else {
                top--; 
                printf("%d\n", stack[top]);
            }
        }
    }
}

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

    process_stack(n);
    return 0;
}

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote