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) {
    // Your logic here
    static int stack[MAX];

    int i = 0;
    char cmd[16];
    int value = 0, count = 0, sp = 0;

    while(i < n)
    {
        count = scanf(" %15s %d", cmd, &value);
        if(count == 2 && strcmp(cmd, "push") == 0)
        {
            if(sp < MAX)
            {
                stack[sp] = value;
                sp++;
            }
            else
            {
                printf("Stack Overflow\n");
            }
        }
        if(count == 1 && strcmp(cmd, "pop") == 0)
        {
            sp--;
            if(sp >= 0)
            {
                printf("%d\n", stack[sp]);
            }
            else
            {
                printf("Stack Underflow\n");
                sp = 0;
            }
        }
        i++;
    }
}

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