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
    int buffer[MAX] = {0};
    char pp[MAX][10];
    int val, top = -1;
    char tempStr[10];
    int k = -1;

    for (int i = 0; i < n; i++)
    {
        scanf("%9s", tempStr);

        if (!strcmp("push", tempStr))
        {
            scanf("%d", &val);
            ++k;
            if (k >= MAX)
            {
                printf("Stack Overflow");
                printf("\n");
                --k; 
            }
            else
            {
                
                buffer[k] = val;
                ++top;
            }
        }
        else
        {
            if (top == -1)
            {
                printf("Stack Underflow");
            }
            else
            {
                printf("%d", buffer[k]);
                --top; 
                --k;
            }
            printf("\n");
        }
    }
}

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