Implement Stack Using Array with Push and Pop Operations

Code

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

#define MAX 10

typedef struct _stack_type{
    int stack[MAX];
    int top;
} stack_type;

stack_type stack = {0};

void process_stack(int n) {
    char cmd[10];
    stack.top = -1;
    for(int i = 0; i < n; i++){
        scanf("%s", cmd);
        //printf("i=%d, cmd=%s\n", i, cmd);
        if (!strcmp(cmd, "push")){
            int val = 0;
            scanf("%d", &val);
            if (stack.top == (MAX-1)){
                printf("Stack Overflow\n");
                //continue;
            }
            else{
                
                stack.top++;
                stack.stack[stack.top] = val;
                
            }
            
        }
        else if(!strcmp(cmd, "pop")){
            //printf("top=%d\n", stack.top);
            if(stack.top == -1){
                printf("Stack Underflow\n");
                //continue;
            }
            else{
                printf("%d\n", stack.stack[stack.top]);
                stack.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