C in 100 Seconds: Stack
Video: C in 100 Seconds: Stack — Push, Pop, Peek | Episode 46 by Taught by Celeste AI - AI Coding Coach
Watch full page →Stack — Push, Pop, Peek
A stack is last in, first out (LIFO). The last item pushed is the first one popped. We build one using an array and a top index.
The Stack Struct
typedef struct {
int items[MAX];
int top;
} Stack;
items holds the data, top tracks the current position. Start at -1 (empty).
Push — Add to Top
void push(Stack *s, int value) {
if (is_full(s)) { printf("Stack overflow!\n"); return; }
s->items[++s->top] = value;
}
++s->top increments first, then stores the value. One line does the move and the store.
Pop — Remove from Top
int pop(Stack *s) {
if (is_empty(s)) { printf("Stack underflow!\n"); return -1; }
return s->items[s->top--];
}
s->top-- returns the value at top, then decrements. The opposite of push.
Peek — Look Without Removing
int peek(Stack *s) {
if (is_empty(s)) return -1;
return s->items[s->top];
}
Same as pop but without the decrement. The stack stays unchanged.
Student Code
Try it yourself: episode46/stack.c