Concept Flow - Peek Top Element of Stack
Start
Check if stack is empty?
Yes→Return None or Error
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.
stack = [10, 20, 30] top = stack[-1] print(top)
| Step | Operation | Stack State | Pointer Changes | Visual State |
|---|---|---|---|---|
| 1 | Start with stack = [10, 20, 30] | [10, 20, 30] | top pointer not set | 10 -> 20 -> 30 (top) |
| 2 | Check if stack is empty | [10, 20, 30] | No change | 10 -> 20 -> 30 (top) |
| 3 | Access top element stack[-1] | [10, 20, 30] | top pointer points to 30 | 10 -> 20 -> 30 (top) |
| 4 | Return top element 30 | [10, 20, 30] | top pointer unchanged | 10 -> 20 -> 30 (top) |
| 5 | Print top element | [10, 20, 30] | No change | 10 -> 20 -> 30 (top) |
| 6 | End | [10, 20, 30] | No change | 10 -> 20 -> 30 (top) |
| Variable | Start | After Step 3 | Final |
|---|---|---|---|
| stack | [10, 20, 30] | [10, 20, 30] | [10, 20, 30] |
| top | undefined | 30 | 30 |
Peek Top Element of Stack: - Check if stack is empty first - Access top element without removing - Return the top element - Stack remains unchanged - Commonly use stack[-1] in Python