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

    // command buffer
    char cb[10][128];
    memset(cb,'\0',sizeof(cb)); // init command buffer

    // first of all we need to store the commands
    for(uint8_t i=0;i<n; i++)
    {
        scanf("%[^\n]%*c",cb[i]);
    }

    // now we need to init our stack
    int stack[MAX];
    int stack_index=-1;
    memset(stack,0,sizeof(stack));


    for (int i=0;i<n; i++)
    {

        // check pop operation
        if (strstr(cb[i],"pop"))
        {
            if (stack_index>=0)
            {
                printf("%d\n",stack[stack_index]);

                stack_index--;

            }

            else
            {
                printf("Stack Underflow\n");
            }

        }

        // check push operation
        else if (strstr(cb[i],"push"))
        {
            // if stack overflow
            if (stack_index>=MAX-1)
            {
                printf("Stack Overflow\n");
            }

            else
            {
                stack_index++;
                // find number
                int num=0;
                sscanf(cb[i],"push %d\n",&num);
                stack[stack_index] = num;
            }
        }


    }
}

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