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.
Stack<Integer> stack = new Stack<>(); stack.push(10); stack.push(20); int top = stack.peek(); System.out.println(top);
| Step | Operation | Nodes in Stack | Pointer Changes | Visual State |
|---|---|---|---|---|
| 1 | Create empty stack | [] | top = null | Stack: [] |
| 2 | Push 10 | [10] | top -> 10 | Stack: 10 -> null |
| 3 | Push 20 | [20, 10] | top -> 20 | Stack: 20 -> 10 -> null |
| 4 | Peek top element | [20, 10] | top unchanged | Stack: 20 -> 10 -> null; Peeked: 20 |
| 5 | Print top element | [20, 10] | top unchanged | Output: 20 |
| Variable | Start | After Step 2 | After Step 3 | After Step 4 | Final |
|---|---|---|---|---|---|
| stack | empty | [10] | [20, 10] | [20, 10] | [20, 10] |
| top pointer | null | points to 10 | points to 20 | points to 20 | points to 20 |
| peeked element | N/A | N/A | N/A | 20 | 20 |
Peek Top Element of Stack: - Check if stack is empty - If empty, return error or null - Else, access top element without removing - Return the top element - Stack remains unchanged after peek
peek() method do in a stack?stack?peek() to view the top element without removing it.top() and getTop() are not valid Stack methods; pop() removes the top element.Stack<Integer> stack = new Stack<>(); stack.push(10); stack.push(20); stack.push(30); System.out.println(stack.peek());
Stack<String> stack = new Stack<>(); System.out.println(stack.peek());
[5, 10, 15] (5 at bottom, 15 at top), which sequence of operations will peek the top element without removing it and then add 20 on top?1. stack.peek(); 2. stack.push(20); 3. stack.pop(); 4. stack.peek();
Pass the test and this pattern moves unknown