#include <stdio.h>
#include <stdint.h>
#include <string.h>
#define MAX 10
typedef struct {
int val[MAX];
int top;
int max;
} tpStackX;
enum {
CMD_INVALID = 0,
CMD_PUSH = 1,
CMD_POP = -1
};
tpStackX StackX = {.top = -1, .max=MAX-1};
int process_input(int *stack_val)
{
char cmd[10];
int val;
*stack_val = 0;
// Try to read "push <num>"
int res = scanf("%s", cmd);
if (res != 1) {
printf("Invalid input\n");
return CMD_INVALID;
}
if (strcmp(cmd, "push") == 0) {
if (scanf("%d", &val) == 1) {
*stack_val = val;
return CMD_PUSH;
} else {
printf("Invalid push command\n");
return CMD_INVALID;
}
} else if (strcmp(cmd, "pop") == 0) {
return CMD_POP;
} else {
printf("Unknown command: %s\n", cmd);
return CMD_INVALID;
}
}
void pop_stack()
{
if(StackX.top >= 0){
printf("%d\n",StackX.val[StackX.top]);
StackX.top--;
}
else{
printf("Stack Underflow\n");
}
}
void push_stack(int val)
{
if(StackX.top < StackX.max){
StackX.top++;
StackX.val[StackX.top] = val;
}
else{
printf("Stack Overflow\n");
}
}
void process_stack(int n) {
// Your logic here
int val = 0;
int cmd = 0;
while(n)
{
cmd = process_input(&val);
if(cmd == 1){
//push
push_stack(val);
}else if(cmd == -1){
//pop
pop_stack();
}
n--;
}
}
int main() {
int n;
scanf("%d", &n);
getchar(); // Consume newline after number
process_stack(n);
return 0;
}
Input
5 push 10 push 20 pop pop pop
Expected Output
20 10 Stack Underflow