All submissions

Implement Stack Using Array with Push and Pop Operations

Code

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

#define MAX 10

typedef struct {
int buffer[MAX];
int size;
int top;
} Stack;


bool isFull(Stack* st)
{
    if(st->size == MAX)
    {
        return true;
    }

    return false;
}

bool isEmpty(Stack* st)
{
    if(st->size == 0)
    {
        return true;
    }

    return false;
}

void push(Stack* st, int n)
{
    if(isFull(st))
    {
        printf("Stack Overflow\n");
        return;
    }

    st->buffer[st->top] = n;
    st->top++;
    st->size++;
}

int pop(Stack* st)
{
  
    if(isEmpty(st))
    {
        return -1;
    }
    st->top--;
    st->size--;
    return st->buffer[st->top];
}

void process_stack(int n) {
    // Your logic here
    Stack st = {.buffer = {0}, .size=0, .top=0};
    char command[5];
    for(int i=0; i<n; i++)
    {
        scanf("%s", command);
        if(strcmp(command, "push") == 0)
        {
            int val;
            scanf("%d", &val);
            push(&st, val);
        }
        else
        {   
            if(isEmpty(&st))
            {
                printf("Stack Underflow\n");
            }
            else
            {
                printf("%d\n", pop(&st));
            }
        
        }
    }
}

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