All submissions

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 arrps=-1,arrpp=0;
    int arr[MAX];
    for(int i=0;i<n;i++){
        char a[10];
        scanf("%s",a);
        //getchar();
        //printf("%s ",a);
        if(strcmp(a,"push")==0){
            arrps+=1;
            int a1=0;
            scanf("%d",&a1);
            //getchar();
            //printf("%d ",a1);
            if(arrps==MAX){
                printf("Stack Overflow\n");
                arrps=MAX-1;
            }
            else{
                arr[arrps]=a1;
                //printf("%d ",arr[arrps]);
            }
        }
        else{
            arrpp=arrps;
            if(arrpp<0){
                arrps=-1;
                printf("Stack Underflow\n");
            }
            else{
                printf("%d\n",arr[arrpp]);
                arrps-=1;
            }
        }
    }
}

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

    process_stack(n);
    return 0;
}

Solving Approach

 

 

 

Loading...

Input

5 push 10 push 20 pop pop pop

Expected Output

20 10 Stack Underflow