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

void process_stack(int n) {
    // Your logic here
    int stack[MAX]; //array of stack sizing MAX = 10
    int top = -1;
    char cmd[20]; //for capturing input command
    int num; //for capturing input value to be pushed

    while(n--){
        fgets(cmd, sizeof(cmd), stdin); //For reading the input command
        if(strncmp(cmd, "push", 4) == 0){ //if detected command is push, continue
            sscanf(cmd, "push %d", &num);

            if(top== MAX-1){
                printf("Stack Overflow\n"); //if stack is full, assert stack overflow
            }else{
                stack[++top] = num; //else push the value in the stack
            }
        }
        else if(strncmp(cmd, "pop", 3) == 0){ //detecting the pop command
            if(top == -1){                    //checking the underflow condition
                printf("Stack Underflow\n");
            } else{
                printf("%d\n", stack[top--]); //else popping the value from stack
            }
        }
    }
}

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

    process_stack(n);
    return 0;
}

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote