#include <stdio.
h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX_SIZE 100
/* A stack is a LIFO (Last In, First Out) structure.
Here we back it with a fixed-size array and an index
`top` that marks the current top element (-1 = empty). */
typedef struct {
int items[MAX_SIZE];
int top;
} Stack;
/* Prepare an empty stack. */
void init(Stack *s) {
s->top = -1;
}
bool isEmpty(Stack *s) {
return s->top == -1;
}
bool isFull(Stack *s) {
return s->top == MAX_SIZE - 1;
}
/* Add a value on top. */
void push(Stack *s, int value) {
if (isFull(s)) {
printf("Stack overflow! Cannot push %d\n", value);
return;
}
s->items[++s->top] = value; /* move top up, then store */
}
/* Remove and return the top value. */
int pop(Stack *s) {
if (isEmpty(s)) {
printf("Stack underflow! Cannot pop\n");
exit(EXIT_FAILURE);
}
return s->items[s->top--]; /* read top, then move top down */
}
/* Look at the top value without removing it. */
int peek(Stack *s) {
if (isEmpty(s)) {
printf("Stack is empty\n");
exit(EXIT_FAILURE);
}
return s->items[s->top];
}
/* Demo */
int main(void) {
Stack s;
init(&s);
push(&s, 10);
push(&s, 20);
push(&s, 30);
printf("Top element: %d\n", peek(&s)); /* 30 */
printf("Popped: %d\n", pop(&s)); /* 30 */
printf("Popped: %d\n", pop(&s)); /* 20 */
printf("Top element: %d\n", peek(&s)); /* 10 */
printf("Is empty? %s\n", isEmpty(&s) ? "yes" : "no");
return 0;
}