Concept Flow - Peek Top Element of Stack
Start
Check if stack is empty?
Yes→Return error or NULL
No
Access top element
Return top element
End
The flow checks if the stack is empty. If not, it accesses and returns the top element without removing it.
int peek(Stack* s) { if (s->top == -1) return -1; // empty return s->arr[s->top]; }
| Step | Operation | Stack Top Index | Stack Array | Pointer Changes | Visual State |
|---|---|---|---|---|---|
| 1 | Start peek operation | 2 | [10, 20, 30] | top points to index 2 | 30 (top) -> 20 -> 10 -> null |
| 2 | Check if stack is empty (top == -1?) | 2 | [10, 20, 30] | No change | 30 (top) -> 20 -> 10 -> null |
| 3 | Access element at top index | 2 | [10, 20, 30] | No change | 30 (top) -> 20 -> 10 -> null |
| 4 | Return top element (30) | 2 | [10, 20, 30] | No change | 30 (top) -> 20 -> 10 -> null |
| 5 | End peek operation | 2 | [10, 20, 30] | No change | 30 (top) -> 20 -> 10 -> null |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|---|
| top | 2 | 2 | 2 | 2 | 2 |
| stack array | [10, 20, 30] | [10, 20, 30] | [10, 20, 30] | [10, 20, 30] | [10, 20, 30] |
| peeked value | N/A | N/A | N/A | 30 | 30 |
Peek Top Element of Stack: - Check if stack is empty (top == -1) - If empty, return error or special value - Else, return element at stack[top] - Does NOT remove element - Stack remains unchanged after peek