Bird
0
0
DSA Cprogramming~3 mins

Why Stack Concept and LIFO Principle in DSA C?

Choose your learning style9 modes available
The Big Idea

What if you could magically undo your last action perfectly every time without confusion?

The Scenario

Imagine you have a pile of plates in your kitchen. You add new plates on top and take plates from the top when you need one.

Now, think about managing tasks or undo actions on your computer manually without any system to keep track of the last action.

The Problem

Without a clear system, it becomes hard to remember which task or action was last added. You might accidentally remove the wrong plate or undo the wrong action.

This manual way is slow, confusing, and causes mistakes because you have no simple way to track the order of tasks or actions.

The Solution

The stack concept uses the Last In, First Out (LIFO) principle, just like the pile of plates.

It keeps track of the last item added and removes it first, making managing tasks or undo actions easy and error-free.

Before vs After
Before
void removeLastTask(char tasks[][20], int *count) {
    if (*count > 0) {
        (*count)--;
    }
}
After
typedef struct Stack {
    int top;
    char items[100][20];
} Stack;

void pop(Stack *stack) {
    if (stack->top >= 0) {
        stack->top--;
    }
}
What It Enables

It enables simple and reliable management of tasks, undo actions, and many other processes where the last item added must be handled first.

Real Life Example

When you press undo in a text editor, the stack remembers your last changes and reverses them in the correct order.

Key Takeaways

Stack follows Last In, First Out (LIFO) principle.

It helps manage tasks or actions in reverse order of addition.

Stack makes undo and redo operations easy and reliable.