All submissions

Implement Stack Using Array with Push and Pop Operations

Code

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

#define MAX 10
int stack[MAX];
int inp=-1;



void process_stack(int n) {
    // Your logic here
    char str[80];
    int i, pawn;
    
    for (i=0; i < n; i++) {
        scanf("%s", str );
        //printf("%s\n", str);
        switch (str[1]) {
            case 'o' : // for pop
            if (inp >= 0 ) {
                printf("%d\n", stack[inp]);
                inp--;
            }
            else {
                printf("Stack Underflow\n");
            }
            break;

            case 'u' : // for push
            scanf("%d", &pawn);
            //printf("%d\n", pawn);
            if (inp < (MAX-1)) {
                inp++;
                stack[inp] = pawn;
            }
            else {
                printf("Stack Overflow\n");
            }
            break;
        }
    }
    
}

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

    process_stack(n);
    return 0;
}

Solving Approach

 

Use single pointer (inp)  initialized to -1, in order to push and pop

 

Loading...

Input

5 push 10 push 20 pop pop pop

Expected Output

20 10 Stack Underflow