Computer Science · Ch 3 — Stack
Applications of Stack
Applications of Stack
A stack is a data structure that follows the Last In, First Out (LIFO) principle — the last item added is the first one removed. This simple rule turns up in many everyday situations and in many programming tasks. The textbook lists both kinds of applications.
Real-life examples of a stack
- A pile of clothes in an almirah — you take the topmost piece first.
- Multiple chairs stacked vertically — you remove the top chair before the one below.
- Bangles worn on the wrist — the last bangle put on is the first one you can take off.
- A pile of boxes of eatables on a pantry or kitchen shelf — again, the top box is the most accessible.
In each case, the order of removal is the reverse of the order of addition.
Programming applications of a stack
Reversing a string
If you push each character of a string onto a stack, then pop them one by one, the characters come out in reverse order. This is a clean, natural way to reverse a string without needing extra index manipulation.
Undo/Redo in editors
Text and image editors keep a stack of changes. When you click Undo, the most recent editing operation is undone — that operation is popped from the stack. When you click Redo, the undone operation is pushed back. The stack ensures that the most recent change is always the first to be reversed.
Browser back button
When you browse the web, each page you visit is pushed onto a history stack. Suppose you start at page P1, then go to P2, then to P3. The stack holds P1 at the bottom, P2 above it, and P3 at the top. Clicking the Back button pops P3 and takes you to P2. Clicking Back again pops P2 and returns you to P1. This is exactly how browser history works — a stack of visited URLs.
Checking matched parentheses in expressions …