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) {
    int stack[MAX] = {};
    int sp = 0;
    for (int i = 0; i < n; i++) {
        char str_buf[16];
        scanf("%s", str_buf);
        if (str_buf[1] == 'u') {
            int val;
            scanf("%i", &val);
            if (sp < MAX) {
                stack[sp] = val;
                sp++;
            } else {
                printf("Stack Overflow\n");
            }
        } else {
            if (sp > 0) {
                sp--;
                printf("%i\n", stack[sp]);
            } else {
                printf("Stack Underflow\n");
            }
        }
    }
}

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