Which statements about the System.Collections.Stack collection are correct?
-
AIt can be used for evaluation of expressions, and all elements can be iterated using an enumerator.
-
BIt maintains a FIFO (first-in, first-out) list and only stores similar types.
-
CIt supports expression evaluation, enumerator-based iteration, and accessing the top element via Peek().
-
DAll of the above statements are correct.
-
ENone of the above statements are correct.
Answer
Correct Answer: It supports expression evaluation, enumerator-based iteration, and accessing the top element via Peek().
Explanation
Introduction / Context:Stack is a fundamental LIFO data structure. Understanding its operations and typical use-cases (such as expression evaluation and recursion emulation) is important for both interviews and real-world coding.
Given Data / Assumptions:
- We discuss System.Collections.Stack (non-generic).
- We evaluate statements about usage pattern (LIFO vs. FIFO), iteration, type restrictions, and top access.
Concept / Approach:Stack supports Push, Pop, and Peek. It is LIFO, not FIFO. Being non-generic, it stores objects and can hold mixed types. It implements IEnumerable, so you can iterate using foreach or an enumerator. Stack is commonly used in parsing and evaluating expressions (e.g., infix to postfix, postfix evaluation).
Step-by-Step Solution:
Expression evaluation → True; stacks are commonly used for operators/operands.Enumerator-based iteration → True; Stack implements IEnumerable.FIFO → False; Stack is LIFO.Similar types only → False; non-generic Stack can store heterogeneous objects.Peek() → True; returns the top element without removal.Verification / Alternative check:Implement a postfix evaluator using a Stack and verify Push/Pop/Peek behavior; iterate with foreach to confirm enumeration.
Why Other Options Are Wrong:A omits Peek(); B asserts FIFO and homogeneity; D contradicts the false parts in A and B; E contradicts the many true aspects.
Common Pitfalls:Confusing Stack (LIFO) with Queue (FIFO), and assuming non-generic collections enforce a single element type.
Final Answer:It supports expression evaluation, enumerator-based iteration, and accessing the top element via Peek().