Prefix to Infix conversion using stack – DSA Course Playlist in C++ – Coding With Clicks

βœ… Prefix to Infix Conversion

πŸ’‘ Rules:

  1. Scan the prefix expression right to left.
  2. If the token is an operand, push it to the stack.
  3. If the token is an operator, pop two operands from the stack.
  4. Combine them as:
    (<operand1> <operator> <operand2>)
  5. Push the resulting string back to the stack.
  6. Final result on the stack is the infix expression.

🧠 Example:

Prefix: + A * B C

Steps:

  • Read C β†’ push
  • Read B β†’ push
  • Read * β†’ pop B and C β†’ (B * C) β†’ push
  • Read A β†’ push
  • Read + β†’ pop A and (B * C) β†’ (A + (B * C))

βœ… Infix: (A + (B * C))

when we say “push the result back to the stack,” like "(B * C)", we’re treating the entire expression as a single operand-like unit, but only in terms of stack processing, not as a literal operand like A, B, or C.

πŸ” Let’s clarify the roles:

  • Real operands: Variables or constants like A, B, C.
  • Operators: Symbols like +, *, /, etc.
  • Sub-expressions like "(B * C)": These are not real operands, but during processing, we treat them as atomic units (strings) to allow nesting.

In Simple Words:

Yes β€” "(B * C)" is treated like an operand only for stack handling purposes, but logically, it’s a composite infix expression made of operands and operators.

πŸ” Why Parentheses Are Needed in Infix

In infix notation, operator precedence matters. For example:

  • A + B * C means A + (B * C) because * has higher precedence than +.

But if you convert prefix + A * B C to plain infix as A + B * C β€” without parentheses β€” it’s unclear whether you meant:

  • (A + B) * C or
  • A + (B * C)

That’s why parentheses are added in the infix result, to make the expression unambiguous, regardless of operator precedence.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top