Step 1: Check Underflow
Always verify if `IsEmpty()` is true. If the stack is completely empty (`top === -1`), you cannot peek. In C++, this causes undefined behavior!
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Peeking allows you to observe the top element of the stack without actually removing it. This is a crucial read-only O(1) operation.
Always verify if `IsEmpty()` is true. If the stack is completely empty (`top === -1`), you cannot peek. In C++, this causes undefined behavior!
Simply access the array at the `top` index: `stack[top]`. You read the value, but you do NOT modify the array.
Unlike `pop()`, the `top` pointer remains exactly where it was. The stack's structural state is entirely unchanged by a peek.