Stack Data Structure
Implement last-in, first-out operations.
What is Stack Data Structure?
A stack exposes only its top: push adds, pop removes, and peek reads the newest item.
Important points
- State the invariants before implementing operations.
- Handle empty, full, and allocation-failure cases.
- Measure time complexity and memory ownership together.
See how it works
Push and pop to see that the last item in is always the first one out.
C and C++ code examples
#include <stdio.h>
typedef struct {
int data[8];
int size;
} Stack;
int push(Stack *stack, int value) {
if (stack->size == 8) return 0;
stack->data[stack->size++] = value;
return 1;
}
int pop(Stack *stack, int *value) {
if (stack->size == 0) return 0;
*value = stack->data[--stack->size];
return 1;
}
int main(void) {
Stack stack = {{0}, 0};
int value;
push(&stack, 10);
push(&stack, 20);
pop(&stack, &value);
printf("%d\n", value);
}
20
#include <iostream>
#include <stack>
int main() {
std::stack<int> values;
values.push(10);
values.push(20);
std::cout << values.top() << '\n';
values.pop();
}
20
C and C++ comparison
The fixed-capacity C implementation must detect overflow and underflow. std::stack manages capacity through its underlying container and offers the same LIFO interface.
Structures and operations are usually separate and allocation is explicit.
Classes and containers can preserve invariants and manage resources automatically.
Practice exercises
Run both versions, then modify them to observe the different language guarantees.
- Add empty and capacity-boundary tests.
- Implement cleanup and verify no leaks remain.
- Compare operation complexity with a standard container.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
All challenges