Implement Stack Using Array with Push and Pop Operations

Code

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

#define MAX 10

typedef struct{
    int arr[MAX];
    int count;
} Stack;

void push(Stack *stk, int val){
    if(stk->count < MAX){
        stk->arr[stk->count++] = val;
    }
    else{
        printf("Stack Overflow\n");
    }
}

void pop(Stack *stk){
    if(stk->count > 0){
        printf("%d\n", stk->arr[--(stk->count)]);
    }
    else{
        printf("Stack Underflow\n");
    }
}

void process_stack(int n) {
    Stack stk = {.count = 0};
    int val = 0;
    char cmd[20];

    for(int i = 0; i < n; i++){
        scanf("%s", cmd);
        if(strcmp(cmd, "push") == 0){
            scanf("%d", &val);
            push(&stk, val);
        }
        else if(strcmp(cmd, "pop") == 0){
            pop(&stk);
        }
    }

}

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

    process_stack(n);
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

5 push 10 push 20 pop pop pop

Expected Output

20 10 Stack Underflow