Bird
0
0
DSA Cprogramming~3 mins

Why Peek Top Element of Stack in DSA C?

Choose your learning style9 modes available
The Big Idea

Peek lets you see the top without breaking the stack--why struggle when you can just peek?

The Scenario

Imagine you have a stack of plates piled up on your kitchen counter. You want to see which plate is on the very top without removing any plates. If you try to lift plates one by one just to see the top, it will be messy and slow.

The Problem

Manually lifting plates to check the top is slow and can cause the stack to fall or get mixed up. Similarly, manually searching through data to find the last added item wastes time and risks errors.

The Solution

The peek operation lets you look at the top item of the stack instantly without removing it. This keeps the stack safe and lets you quickly check the latest item added.

Before vs After
Before
int topElement(int stack[], int size) {
    return stack[size - 1]; // manually access last element
}
After
int peek(Stack *stack) {
    if (stack->top == -1) return -1; // empty
    return stack->items[stack->top];
}
What It Enables

Peek makes it easy to check the most recent item added without disturbing the stack.

Real Life Example

When undoing actions in a text editor, peek helps see the last action without removing it, so you can decide whether to undo or not.

Key Takeaways

Manual checking of the top item is slow and risky.

Peek quickly shows the top item without removing it.

Useful in undo features, expression evaluation, and more.