A stack is a linear data structure that follows the Last In, First Out (LIFO) principle. Think of it like a stack of books on a desk — you can only add or remove books from the very top.
Imagine a stack of heavy textbooks. When you finish reading a new book, you place it on top of the pile. When you need a book to read, you take the one on top. You never take a book from the bottom because the pile would collapse!
Think of a stack of Heavy Books.
LIFO: Last In, First Out
Take (POP)
You can only take the TOP book.
Place (PUSH)
You can only place a book on the TOP.
Last In, First Out. The last book you place is the first one you read.
Your Eyes. Points to highest book.
Placing a book (Top ↑).
Removing top book (Top ↓).
Looking at it without touching.
Let's understand the core rules.
The Stack of Books Analogy
Imagine a heavy pile of books on your desk.
1. The books are stacked one on top of the other.
2. If you want to add a new book to the pile, it has to go on the very top.
3. If you want to read a book, you have to take the one on the very top.
4. You cannot access the book at the bottom without first removing all the books resting on top of it.
This is exactly how a Stack works in computer science.
Core Principle: LIFO
LIFO stands for Last In, First Out.
The book you placed on the pile last will be the first one you take off.
Essential Terminology
Stacks are incredibly useful for tracking state or reversing order. Any time you need to go back to exactly where you just came from (like hitting the 'Back' button in a browser, or 'Undo' in a text editor), you are using a stack.
"What principle does a stack follow, and what does it mean?"
A stack follows the LIFO principle (Last In, First Out). It means the most recently added item is the first one to be removed, like taking the top book from a pile.