Stack Data Structure
A stack exposes only its top: push adds, pop removes, and peek reads the newest item.
What is Stack Data Structure?
A stack exposes only its top: push adds, pop removes, and peek reads the newest item.
Implement last-in, first-out operations.
Important points
- State the invariants before implementing operations.
- Handle empty, full, and allocation-failure cases.
- Measure time complexity and memory ownership together.
C and C++ code examples
main.c
#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
C++
main.cpp
#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.
C
Structures and operations are usually separate and allocation is explicit.
C++
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.