Stack Assignment
Stack Assignment
1. Initialize an empty stack for holding operators and an empty list (or string) for the output postfix
expression.
2. Iterate through each character in the infix expression:
If the character is an operand, add it directly to the postfix expression.
If the character is an opening parenthesis ‘(‘, push it onto the stack.
If the character is a closing parenthesis ‘)’, repeatedly pop from the stack and add to the postfix
expression until an opening parenthesis ‘(‘ is encountered on the stack. Pop and discard the
opening parenthesis from the stack.
If the character is an operator (e.g., +, -, *, /):
While the stack is not empty, and the top of the stack has an operator with greater or equal
precedence than the current operator, pop the stack and add the operator to the postfix
expression.
Push the current operator onto the stack.
3. After reading the infix expression (if reach end of expression), pop any remaining operators from the
stack and add them to the postfix expression.
4. Return the postfix expression.
Operator Precedence and Associativity
Operator precedence determines how operators are prioritized in expressions. For example, multiplication (*)
and division (/) have higher precedence than addition (+) and subtraction (-).
Associativity (usually left-to-right for most operators) determines the order of operations when two operators
share the same precedence.
Example of Infix to Postfix Conversion
Example 1:
Infix Expression : A+(B*C+D)/E
Input Postfix
Stack Action
Token Expression
‘+’ operator has less precedence than ‘*’, so pop * and add
+ +(+ ABC* to
expression string
Q:What is the main reason that computers can directly execute instructions represented in
postfix notation?
Ans: Postfix notation is the standard format for all programming languages
Postfix notation is easier to understand
Postfix notation does not require interpreting nested brackets or determining precedence rules
Postfix notation is more efficient to store in memory
– – FED-^ ‘-‘ operator has less precedence than ‘^’, so pop ^ and add to expression
string
FED-^C-BA++ Pop all operators one by one as we have reached end of the expression