Bird
Raised Fist0
DSA Javaprogramming~10 mins

Peek Top Element of Stack in DSA Java - Execution Trace

Choose your learning style10 modes available
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.
Execution Sample
DSA Java
Stack<Integer> stack = new Stack<>();
stack.push(10);
stack.push(20);
int top = stack.peek();
System.out.println(top);
This code pushes two elements onto the stack and then peeks at the top element, printing it.
Execution Table
StepOperationNodes in StackPointer ChangesVisual State
1Create empty stack[]top = nullStack: []
2Push 10[10]top -> 10Stack: 10 -> null
3Push 20[20, 10]top -> 20Stack: 20 -> 10 -> null
4Peek top element[20, 10]top unchangedStack: 20 -> 10 -> null; Peeked: 20
5Print top element[20, 10]top unchangedOutput: 20
💡 Peek operation ends after returning the top element without modifying the stack.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
stackempty[10][20, 10][20, 10][20, 10]
top pointernullpoints to 10points to 20points to 20points to 20
peeked elementN/AN/AN/A2020
Key Moments - 3 Insights
Why does peek not remove the top element from the stack?
Peek only accesses the top element without changing the stack, as shown in step 4 where the stack remains [20, 10] and the top pointer is unchanged.
What happens if we peek when the stack is empty?
The flow in concept_flow shows that if the stack is empty, peek returns an error or null, preventing access to a non-existent element.
Why is the top pointer unchanged after peek?
Because peek only reads the top element without popping it, the top pointer remains pointing to the same node, as seen in step 4 of the execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3, what is the top element of the stack?
A10
Bnull
C20
DEmpty
💡 Hint
Check the 'Nodes in Stack' and 'Pointer Changes' columns at step 3.
At which step does the peek operation occur?
AStep 4
BStep 2
CStep 3
DStep 5
💡 Hint
Look for the 'Operation' column mentioning 'Peek top element'.
If the stack was empty, what would the peek operation return according to the concept_flow?
AThe top element
BAn error or null
CThe bottom element
DThe entire stack
💡 Hint
Refer to the decision branch in the concept_flow diagram for empty stack check.
Concept Snapshot
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
Full Transcript
The peek operation on a stack first checks if the stack is empty. If it is, it returns an error or null to avoid accessing a non-existent element. If not empty, it accesses the top element without removing it, leaving the stack unchanged. This is shown in the execution where after pushing 10 and 20, peek returns 20 without modifying the stack. The top pointer remains pointing to the same node after peek. This operation is useful to see the current top without altering the stack's contents.

Practice

(1/5)
1. What does the peek() method do in a stack?
easy
A. Checks if the stack is empty
B. Removes and returns the top element
C. Adds a new element to the top
D. Returns the top element without removing it

Solution

  1. Step 1: Understand the peek method purpose

    The peek method is designed to look at the top element of the stack without changing the stack.
  2. Step 2: Compare with other stack methods

    Unlike pop, peek does not remove the element; it only returns it.
  3. Final Answer:

    Returns the top element without removing it -> Option D
  4. Quick Check:

    peek() = top element without removal [OK]
Hint: Peek shows top without removing it [OK]
Common Mistakes:
  • Confusing peek with pop
  • Thinking peek adds elements
  • Assuming peek checks emptiness
2. Which of the following is the correct syntax to peek the top element of a Java Stack named stack?
easy
A. stack.peek();
B. stack.top();
C. stack.getTop();
D. stack.pop();

Solution

  1. Step 1: Recall Java Stack method names

    The Java Stack class uses peek() to view the top element without removing it.
  2. Step 2: Check other options for correctness

    top() and getTop() are not valid Stack methods; pop() removes the top element.
  3. Final Answer:

    stack.peek(); -> Option A
  4. Quick Check:

    Correct syntax for peek is stack.peek() [OK]
Hint: Use stack.peek() to view top element [OK]
Common Mistakes:
  • Using pop() instead of peek()
  • Using non-existent methods like top()
  • Missing parentheses in method call
3. What will be the output of the following Java code?
Stack<Integer> stack = new Stack<>();
stack.push(10);
stack.push(20);
stack.push(30);
System.out.println(stack.peek());
medium
A. 10
B. 30
C. 20
D. StackEmptyException

Solution

  1. Step 1: Trace the push operations

    Elements pushed in order: 10 (bottom), 20, then 30 (top).
  2. Step 2: Understand peek output

    peek() returns the top element without removing it, which is 30.
  3. Final Answer:

    30 -> Option B
  4. Quick Check:

    Top element after pushes = 30 [OK]
Hint: Peek shows last pushed element [OK]
Common Mistakes:
  • Confusing peek with pop output
  • Assuming peek returns bottom element
  • Expecting exception on non-empty stack
4. Identify the error in the following code snippet that tries to peek the top element of a stack:
Stack<String> stack = new Stack<>();
System.out.println(stack.peek());
medium
A. Throws EmptyStackException at runtime
B. Prints empty string
C. Compilation error: peek() not found
D. No error, prints null

Solution

  1. Step 1: Check stack initialization and usage

    The stack is created but no elements are pushed before peek is called.
  2. Step 2: Understand peek behavior on empty stack

    Calling peek() on an empty stack throws EmptyStackException at runtime.
  3. Final Answer:

    Throws EmptyStackException at runtime -> Option A
  4. Quick Check:

    peek() on empty stack throws exception [OK]
Hint: Peek on empty stack throws exception [OK]
Common Mistakes:
  • Assuming peek returns null if empty
  • Expecting compile-time error
  • Thinking it prints empty string
5. Given a stack with elements [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();

Select the correct order of operations to achieve this.
hard
A. 3, 1, 2
B. 2, 1
C. 1, 2
D. 1, 3, 2

Solution

  1. Step 1: Peek top element without removing

    Operation 1 (stack.peek()) returns 15 without removing it.
  2. Step 2: Add 20 on top

    Operation 2 (stack.push(20)) adds 20 on top, so stack becomes [5, 10, 15, 20].
  3. Final Answer:

    1, 2 -> Option C
  4. Quick Check:

    Peek then push = 1, 2 [OK]
Hint: Peek first, then push new element [OK]
Common Mistakes:
  • Popping before peek removes top
  • Pushing before peek changes top
  • Incorrect operation order
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard