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>

#define MAX 10
typedef struct {
    uint8_t stack[MAX];
    uint8_t count = 0;
} Stack;

void pushStack(Stack *stk, int val){
    if (stk->count == MAX){
        printf("Stack Overflow\n");
        return;
    }
    stk->stack[stk->count] = val;
    stk->count++;
};

void popStack(Stack *stk){
    if (stk->count == 0){
        printf("Stack Underflow\n");
        return;
    }
    stk->count--;
    printf("%d\n", stk->stack[stk->count]);
    
};
void process_stack(int n) {
    // Your logic here
    int val = 0;
    char cmd[20];
    Stack stk;
    for (int i = 0; i < n; i++) {
    scanf("%s", cmd);
        if(strcmp(cmd, "push") == 0){
            scanf("%d", &val);
            pushStack(&stk, val);
        }
        else if(strcmp(cmd, "pop") == 0){
            popStack(&stk);
        }
    }
}

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

    process_stack(n);
    return 0;
}

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote