Data Structures
What Is a Stack in Data Structures?
A stack is a last-in, first-out (LIFO) data structure: the most recently added item is the first one removed, like a pile of plates.
Definition
A stack holds items so that the last one added is the first one taken out, which is called last in, first out (LIFO). Think of a pile of plates: you add and remove from the top.
Stacks power the undo button, the browser back button, expression parsing and the call stack that tracks function calls.
How it works
The main operations are push (add to the top), pop (remove from the top) and peek (look at the top without removing it). All three take O(1) time.
In Python a list works as a stack with append and pop. In Java, use ArrayDeque.
When one function calls another, the computer pushes a frame holding its local variables onto the call stack and pops it when the function returns. Too many nested calls use up that space, which is a stack overflow.