Which data structure is required to convert the infix to prefix notation?

2023

Which data structure is required to convert the infix to prefix notation?

Answer: B. StackConcept: An infix-to-prefix conversion has to re-order operators around their operands while respecting precedence and right-to-left associativity. A stack is…

  1. A.

    Queue

  2. B.

    Stack

  3. C.

    Linked list

  4. D.

    More than one of the above

  5. E.

    None of the above

Attempted by 2240 students.

Show answer & explanation

Correct answer: B

Concept: An infix-to-prefix conversion has to re-order operators around their operands while respecting precedence and right-to-left associativity. A stack is built for exactly this: its Last-In-First-Out (LIFO) discipline lets an operator be pushed and held back until every operand or sub-expression it governs has been read, and only then popped into its final position -- precisely the deferred, undo-style handling this conversion needs.

Application: The standard algorithm runs in five steps:

  1. Reverse the given infix expression character by character, swapping every '(' with ')' and every ')' with '('.

  2. Scan the reversed string left to right. Send each operand straight to the output. Push each opening parenthesis onto the stack, and on a closing parenthesis, pop operators into the output until the matching opening parenthesis is popped off and discarded.

  3. For each operator, before pushing it, pop into the output any operator already on top of the stack whose precedence is higher than the current operator's, or equal to it when the current operator is right-associative (such as exponentiation); operators of equal precedence that are left-associative (such as +, -, *, /) are pushed without popping, which preserves their original grouping once the string is reversed back.

  4. When the scan ends, pop every operator still on the stack and append it to the output. This gives the postfix form of the reversed expression.

  5. Reverse that postfix string; the result is the prefix form of the original expression.

Cross-check: Apply this to (A + B) * C. Reversing gives C * (B + A); scanning with the stack (pushing '(' , sending B and A straight to output, popping '+' then discarding the matching '(' at ')' , then popping '*' at the end) produces the postfix string C B A + *; reversing that gives * + A B C, which is indeed the correct prefix form of (A + B) * C. The associativity rule also matters: for equal-precedence right-associative operators such as exponentiation (A^B^C), the scan must pop on equal precedence too, correctly giving ^A^BC instead of the wrong ^^ABC that a blanket never-pop-on-equal rule would produce.

Result: Every step of this algorithm depends on a stack to hold pending operators in the correct release order, so a stack is the data structure required for infix-to-prefix conversion.

Explore the full course: Rssb Basic Computer Instructor

Loading lesson…