Peek Operation
Peek gives you a look at whatever's currently on top of the stack, but it leaves the stack exactly as it was: nothing gets popped.
How Does It Work?
A stack only ever exposes its top. Peek reads the value sitting there and hands it back, but unlike pop it never moves the top pointer, so the stack that comes out is the same stack that went in.
Example: Peeking at a stack
- Current stack, 7 on top
- Peek → returns 7, and the stack is left exactly as it was
- Pop → returns 7 and removes it, so 3 becomes the new top
- Peek → returns 3, again without removing anything
Notice the size line under each diagram: it only changes on the pop step. That is the whole difference between the two operations — both return the top value, but only pop takes it off.
- Time Complexity: O(1)
- Space Complexity: O(1)
The peek operation is useful when you need to inspect the top element before deciding whether to pop it or push another element onto the stack.