Peek (or Top) Operation
You'll learn how to inspect the top element of a stack without modifying it.
The Core Idea
The peek operation (also called top) lets you look at the element on top of the stack without removing it. Unlike pop, which removes and returns the top element, peek simply returns a copy or reference to that element while leaving the stack unchanged.
Think of it like looking at the top card of a deck without picking it up—you can see what it is, but the deck remains exactly as it was.
Why Peek Is Useful
Sometimes you need to check what's on top of the stack to make a decision, but you're not ready to remove it yet. For example:
- Validation: "Is the top element what I expect before I pop it?"
- Conditional logic: "If the top is an operator, do one thing; if it's a number, do another."
- Non-destructive inspection: You want to examine the stack's state without altering it during debugging or algorithm execution.
How It Works
The peek operation:
- Checks if the stack is empty (returns an error or special value if so)
- Returns the value at the top position
- Leaves the stack completely unchanged
After a peek, the next pop will still return the same element you just peeked at.
Key Takeaway:
Peek lets you view the top element of a stack without removing it, enabling non-destructive inspection and conditional decision-making before performing other operations.