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.
Free account
Sign up to read the rest of this lesson: 7 more sections, 5 drawings, a dry-run simulator and code in JavaScript, Python, Java and C++.
Still to come
Was this helpful?