The Stack Rules: No Shortcuts Allowed
In a stack, you are restricted to adding and removing elements only from the top. This is a critical rule to remember because it means you can't skip the queue or cheat the system; you have to work your way down.
A Real-World Scenario
Let's visualize this with our example stack that has a series of numbers: 1
, 434
, 619
, 420
, 316
, 1024
, and 6661
.
1// ____________
2// | 1 | ← Top of the stack
3// | |
4// | 434 |
5// | |
6// | 619 |
7// | |
8// | 420 | ← We want to remove this
9// | |
10// | 316 |
11// | |
12// | 1024 |
13// | |
14// | 6661 | ← Bottom of the stack
15// |____________|
How to Remove a Middle Element?
Say, for instance, you want to remove 420
from this stack. You can't just reach in and pull it out. You have to remove elements from the top down. So, you'll need to execute the pop
operation multiple times to get to 420
.
Here's how you'd code that:
1// removing elements '1', '434', '619', '420' using a loop
2for (let i = 0; i < 4; i++) {
3 stack.pop();
4}
Or, you could specify each pop
operation like so:
1stack.pop(); // removes element 1
2stack.pop(); // removes element 434
3stack.pop(); // removes element 619
4stack.pop(); // finally removes element 420
Either way, the point is: You have to remove the items in the reverse order they were added. And this is the core principle that makes a stack a Last-In, First-Out (LIFO) data structure.