All submissions

Implement Stack Using Array with Push and Pop Operations

Code

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

#define MAX 10

void extractNum(char* dest_, char* src_){
    for(int i=5;i<strlen(src_);i++){
        dest_[i-5] = src_[i];
    }
    dest_[strlen(src_)-5+1] = '\0';
}
void process_stack(int n) {
    char STACKstr[MAX][10];
    int STACKtop = 0;
    char str[MAX];
    for(int i=0;i<n;i++){
        scanf("%[^\n]s",str);
        getchar();
        //POP case
        if(strcmp(str,"pop")==0){
            if((STACKtop)-1 < 0) printf("Stack Underflow\n");
            else {
                (STACKtop)--;
                printf("%s\n",STACKstr[STACKtop]);
                }
        }
        //PUSH case
        else{
            char number[10]={0};
            extractNum(number,str);
            if((STACKtop+1) > MAX) printf("Stack Overflow\n");
            else{
                strcpy(STACKstr[STACKtop],number);
                (STACKtop)++; //preparation nouvel espace
            }
        }
        //saut de ligne apres chaque printf
        //if(i < n-1) printf("\n");
    }
}

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