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.
#include <iostream> #include <stack> using namespace std; int main() { stack<int> s; s.push(10); s.push(20); int top = s.top(); cout << top; return 0; }
| Step | Operation | Nodes in Stack | Pointer Changes | Visual State |
|---|---|---|---|---|
| 1 | Initialize empty stack | [] | head = null | null |
| 2 | Push 10 | [10] | head -> 10 | 10 -> null |
| 3 | Push 20 | [20, 10] | head -> 20 | 20 -> 10 -> null |
| 4 | Peek top element | [20, 10] | head -> 20 | 20 -> 10 -> null |
| 5 | Return top element value | 20 | head unchanged | 20 -> 10 -> null |
| 6 | End | [20, 10] | head -> 20 | 20 -> 10 -> null |
| Variable | Start | After Step 2 | After Step 3 | After Step 4 | Final |
|---|---|---|---|---|---|
| stack contents | [] | [10] | [20, 10] | [20, 10] | [20, 10] |
| head pointer | null | points to 10 | points to 20 | points to 20 | points to 20 |
| top element value | undefined | undefined | undefined | 20 | 20 |
Peek Top Element of Stack: - Check if stack is empty - If not empty, access top element - Return top element without removing - Stack remains unchanged - Useful to see current top value
peek() operation do in a stack?stk in C++ STL?top().stk.top(); returns the top element without removing it.std::stack<int> stk; stk.push(10); stk.push(20); stk.push(30); std::cout << stk.top() << std::endl;
stk.top() returns 30 without removing it.stk:int topElement = stk.peek();
peek().top(), so stk.top() should be used.stk with elements [5, 10, 15] pushed in that order, which code snippet correctly prints the top element without removing it and then prints the stack size?stk.top() which returns top element without removing it.stk.size() remains 3.Pass the test and this pattern moves unknown