88. Implement Stack Using Array with Push and Pop Operations

Back To All Submissions
Previous Submission
Next Submission

Code

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

#define MAX 10

typedef struct 
{
    int buffer[MAX];
    int peek;
} Stack;

void stack_init(Stack *s)
{
    memset(s->buffer, 0, MAX);
    s->peek = 0;
}

void stack_push(Stack * s, int value)
{
    if (s->peek == MAX)
    {
        printf("Stack Overflow\n");
        return;
    }

    s->buffer[s->peek] = value;
    s->peek++;
}

bool stack_pop(Stack * s, int * value)
{
    if (s->peek == 0)
    {
        printf("Stack Underflow\n");
        return false;
    }

    *value = s->buffer[s->peek - 1];
    s->peek--;
    return true;
}

void process_stack(int n) {
    // Your logic here
    Stack s;
    stack_init(&s);

    for (int i = 0; i < n; i++)
    {
        char command[10];
        int value;

        while (scanf("%s", command) != EOF) {
        
            if (strcmp(command, "push") == 0) {
                scanf("%d", &value);
                stack_push(&s, value);
            } 
            else if (strcmp(command, "pop") == 0) {
                int res;
                if (stack_pop(&s, &res))
                {
                    printf("%d\n", res);
                }
            }
        }
    }
}

int main() {
    int n;
    scanf("%d", &n);
    getchar(); // Consume newline after number

    process_stack(n);
    return 0;
}

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote