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];
    int pos = 0;
    for (size_t i=0; i<n; i++){
        char mode[4];
        int value;
        scanf("%s %d", &mode, &value);
        // printf("'%s' - '%d' = ", mode, value);

        // POP
        if (strcmp(mode, "push")){
            // printf("POP\n");
            if (pos == 0){
                printf("Stack Underflow\n");
            } else {
                printf("%d\n", stack[pos]);
                pos = pos - 1;
            }

        //PUSH
        } else {
            // printf("PUSH\n");
            if (pos == (MAX)) {
                printf("Stack Overflow\n");
            } else {
                pos = pos + 1;
                stack[pos] = value;
            }
        }
    }
}

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

    process_stack(n);
    return 0;
}

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote