#include <stdio.h>
#include <stdint.h>
#include <string.h>
#define MAX 10 // Maximum amount of numbers that stack can hold
#define EMPTY -1 // Defines the empty stack
typedef struct stack{
int numbers[MAX]; // array of numbers.
int top; // Index tracking.
}stack_t;
// Declare and initialize the global stack
stack_t stack_cli = {
.numbers = {0}, // All numbers of the array to 0
.top = -1 // Indexing pointer at -1
};
/**
* Push operation to the stack.
*/
void push(stack_t *stack, int n) {
if (stack->top == (MAX - 1)) {
printf("Stack Overflow\n"); // Print overflow if stack is full.
} else {
stack->numbers[++stack->top] = n; // Push value into the stack.
}
}
/**
* Pop operation from the stack.
*/
void pop(stack_t *stack) {
if (stack->top == EMPTY) {
printf("Stack Underflow\n"); // Print underflow if stack is empty.
} else {
printf("%d\n", stack->numbers[stack->top]); // Pop and print the top value from the stack
stack->top--;
}
}
void process_stack(int n) {
for (int i=0; i<n; i++) {
char operation[20] = {0};
int number;
// Read the command from STDIN
fgets(operation, sizeof(operation), stdin);
if (strncmp(operation, "push", 4) == 0) { // Push operation
// Extract the number that needs to be inserted to the stack.
sscanf(operation + 5, "%d", &number);
// Perform the operation
push(&stack_cli, number);
} else if (strncmp(operation, "pop", 3) == 0) { // Pop operation
// Perform the operation
pop(&stack_cli);
} else {
printf("Undefined command\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