110 likes | 268 Views
Reverse Polish Expressions. Some general observations about what they are and how they relate to infix expressions.
E N D
Reverse Polish Expressions • Some general observations about what they are and how they relate to infix expressions. • These 9 slides provide details about exactly what operations are performed on stacks to both evaluate RPN expressions (which you DO NOT have to do in lab - but should know about), and transform infix expressions to postfix (which you DO have to do for lab).
Postfix notation • Given the standard infix notation: 7*5-3 • The RPN expression is: 75*3- • We made it like this by placing operators last (after the operands)
Evaluating RPN expressions • RPN expressions are best evaluated using a stack. • Stacks are LIFO (last in first out)
Evaluation example Expression: 7 5 * 3 - 7*5 35-3 push push 32 push pop push push pop pop pop pop 7 7 35 35 32 5 3 empty top -1 0 1 0 1 0 -1
Operator placement • It makes a big difference how operators are placed: • 7*5-3 = 32 • RPN: 75*3- = 32 • RPN: 753*- = -8 same as infix 7-(5*3) • RPN: 75-3* = 6 same as infix (7-5)*3
Converting infix expressions • To convert an infix expression to a postfix expression means building a stack of operators. • The operators have priority levels • highest: */, next highest: +-, lowest (
Converting infix to postfix Expression: 7 * 5 - 3 7 5 3 - * check priority pop push pop push * * - - empty top -1 0 0,-1 -1,0 0 -1
Another example: 6*7*8*9-3 Expression: 6*7*8*9-3 6789***3- check priority push pop pop pop pop push - * * * * * * * * * * * * empty top 0 1 2 2 1 0 0 -1
Things to notice • In the previous example, the subtraction operator could not be pushed on to the stack until all operators of higher priority had been popped off. • THE END