A stack is a collection where you can only add or remove items at one end, called the top. The last item you put in is always the first one you take out. That rule has a name: LIFO — last in, first out.
In a cafeteria, clean plates are stacked on top of each other. You put a clean plate on top, and you take the plate from the top. Nobody pulls a plate out of the middle. A stack in programming follows exactly the same rules:
Every one of these is O(1): none of them ever has to look past the top item, no matter how tall the stack gets.
Members only · free account
The rest of this lesson, with 7 more sections, 5 drawings, a dry-run simulator and code in JavaScript, Python, Java and C++, opens with a free account.
Was this helpful?
Not ready yet? The Arrays course is free to read, no account needed.
In the rest of this lesson