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) {
    char c[7];
    int nr, a[MAX] = {0}, idx = -1;
    while (n > 0) {
        scanf("%s", c);
        if (c[1] == 'u') {
            if (idx + 1 < MAX) {
                nr = 0;
                scanf("%s", c);
                for (int i = 0; c[i] != '\0'; i++) {
                    nr = nr * 10 + (c[i] - '0');
                }
                idx++;
                a[idx] = nr;
            } else {
                printf("Stack Overflow");
                if (n > 1) printf("\n");
                scanf("%s", c);
            }
        } else {
            if (idx >= 0) {
                printf("%d", a[idx]);
                idx--;
            } else {
                printf("Stack Underflow");
            }
            if (n > 1) printf("\n");
        }
        n--;
    }
}

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

    process_stack(n);
    return 0;
}

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote