Elements pushed in order: 10, then 20, then 30. Stack top is last pushed element 30.
Step 2: Check top() output
stk.top() returns 30 without removing it.
Final Answer:
30 -> Option A
Quick Check:
Last pushed = top = 30 [OK]
Hint: Top is last pushed element [OK]
Common Mistakes:
Confusing top with bottom element
Assuming top removes element
Thinking output is 20 or 10
4. Identify the error in the following code snippet that tries to peek the top element of a stack named stk:
int topElement = stk.peek();
medium
A. stk should be declared as a queue
B. peek() is not a valid method in C++ STL stack
C. topElement should be a pointer
D. stk.pop() should be used instead
Solution
Step 1: Check method availability in C++ STL stack
C++ STL stack does not have a method named peek().
Step 2: Correct method to peek top element
The correct method is top(), so stk.top() should be used.
Final Answer:
peek() is not a valid method in C++ STL stack -> Option B
Quick Check:
Use stk.top() not stk.peek() [OK]
Hint: Use .top(), not .peek() in C++ STL [OK]
Common Mistakes:
Using peek() method which doesn't exist
Confusing pop() with peek()
Thinking topElement must be pointer
5. Given a stack 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?