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; // top of stack

    char command[20];
    int value;

    for (int i = 0; i < n; i++) {
        fgets(command, sizeof(command), stdin);
        
        // Remove newline at end
        if (command[strlen(command)-1] == '\n') 
            command[strlen(command)-1] = '\0';

        if (strncmp(command, "push", 4) == 0) {
            sscanf(command + 5, "%d", &value); // Extract value after "push "
            if (top == MAX - 1) {
                printf("Stack Overflow\n");
            } else {
                top++;
                stack[top] = value;
            }
        } else if (strcmp(command, "pop") == 0) {
            if (top == -1) {
                printf("Stack Underflow\n");
            } else {
                printf("%d\n", stack[top]);
                top--;
            }
        }
    }
}

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