Last in first out
A stack serves elements in last in first out order: the most recently added item is the first one removed. It exposes just a few operations, usually push to add, pop to remove the top, and peek to inspect the top without removing it.
Backing it with an array
The simplest implementation sits on a dynamic array. You keep a top index marking the position just past the last element:
- Push writes at the top index, then increments it.
- Pop decrements the index, then reads the element it now points at.
- Peek reads the element just below the top index.
Because all action happens at one end, no shifting is ever needed, so push and pop are cheap. Push can occasionally trigger a resize when the array fills, but that cost averages out the same way it does for a plain dynamic array.
Why the array fits
The array end behaves exactly like a stack top: adding and removing at the tail never disturbs the other elements, which is precisely the access pattern a stack requires.
Key idea
A stack is an array plus a top index, where push and pop act only at the array end, giving last in first out order without shifting elements.