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
    int top = -1;
    int arr[MAX] = {0};
    for(int x=1;x<=n;x++)
    {
        char input[5];
        scanf("%s", input);
        if(strcmp(input, "push") == 0)
        {
            int i;
            scanf("%d", &i);
            if(top == MAX-1){
                printf("Stack Overflow\n");
                continue;
            }    
            arr[++top] = i;
        }
        else
        {
            if(top == -1){
                printf("Stack Underflow\n");
                continue;
            }   
            printf("%d\n",arr[top--]);
        }
    }
}

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