Computer Science · Ch 3 — Stack
Humans naturally understand infix expressions like x + y / z. We know from the BODMAS rule that division has higher precedence than addition, so we evaluate y / z first, even though the + operator appears earlier when reading left to right. A computer, however, does not have this built-in knowledge of operator precedence. If we simply feed it an infix expression, it would not know which operation to perform first without extra rules.
Postfix notation (also called Reverse Polish Notation) solves this problem. In a postfix expression, the operators are placed after their operands, and the order of operators already reflects the correct precedence. This means a computer can evaluate the expression in a single left-to-right scan, without needing to worry about precedence or parentheses. The same logic applies to prefix notation, where operators come before operands.
The conversion from infix to postfix is therefore a crucial step in expression evaluation. A stack is the perfect data structure for this job because it can temporarily hold operators (and parentheses) until their correct position in the output is determined.
The algorithm processes the infix expression character by character, from left to right. It uses two things:
postExp) to build the final postfix expression.Here are the steps:
postExp and an empty stack.inExp.inExp (from left to right), do the following:
x, y, or a number 8): Append it directly to postExp.(: Push it onto the stack.): Pop operators from the stack one by one and append each to postExp until you pop the matching left parenthesis (. Discard both parentheses (do not append them to postExp).+, -, *, /):
Drawn by us to help you understand the concept clearly, and verified to make sure it's accurate. For exams, practice from your NCERT textbook's own diagram.
This figure shows, column by column, exactly how the Infix-to-Postfix conversion algorithm processes the expression (x + y)/(z*8) one symbol at a time, using a stack to hold operators and parentheses.
The rule is simple: an operand (like x, y, z, 8) is appended straight to the output string postExp. An operator or ( is pushed onto the stack. A ) pops everything off the stack and appends it to postExp until the matching ( is found (which is then discarded, not appended). At the very end, anything still left on the stack is popped …