All submissions

Implement Stack Using Array with Push and Pop Operations

Code

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

#define MAX 10

void process_stack(int n) {
    int stack[MAX];
    int top = -1;
    char line[64];

    for (int i = 0; i < n; i++) {
        if (!fgets(line, sizeof(line), stdin)) break;

        // Skip leading whitespace
        char *p = line;
        while (*p == ' ' || *p == '\t') p++;

        if (strncmp(p, "push", 4) == 0) {
            // Move past "push" and spaces to read the value
            p += 4;
            while (*p == ' ' || *p == '\t') p++;

            int val;
            if (sscanf(p, "%d", &val) == 1) {
                if (top == MAX - 1) {
                    printf("Stack Overflow\n");
                } else {
                    stack[++top] = val;
                }
            }
            // If no value found after "push", ignore the line silently
        } else if (strncmp(p, "pop", 3) == 0) {
            if (top == -1) {
                printf("Stack Underflow\n");
            } else {
                printf("%d\n", stack[top--]);
            }
        }
        // Unknown commands are ignored
    }
}

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

    process_stack(n);
    return 0;
}

Solving Approach

 

 

 

Loading...

Input

5 push 10 push 20 pop pop pop

Expected Output

20 10 Stack Underflow