Infix to Postfix Conversion CS212 & CS240 DJ Foreman
The algorithms convert infix notation to postfix use a stack of operators and operands NOTE: you can either place the data in the stack as you read it OR put it all in a temporary queue, then pull from that queue evaluate a postfix expression uses stack from step 1 evaluate an infix expression use (1) and (2) together
Infix to Postfix (algorithm 1) while (more input) // ended by a $ if '(' push it on stack with priority (precedence) 0 if operand - send to output (enqueue – separate from temp queue) if ')' output operators till '('. Unstack & discard the '('. Discard the ')' if operator while precedence (operator) < precedence (top) unstack and output operators unstack and enqueue any operators remaining on stack Result will be a queue in postfix order Precedence (high to low): ^ * / + - (
Evaluating Postfix (algorithm 2) while (more input) if (operand) push on stack if (operator) apply to top 2 stack items and replace them (on the stack) with the result of the operation E.g.; given the queue form algorithm 1 has: now has 23+ (where the 2 is in the front), the stack will contain the 2 at the bottom, the 3 above it and seeing the +, you pull the 3 and 2, do the addition, putting the 5 back on top When no input remains, remaining item on the operand stack is value of the expression