Reverse Polish Notation Using Stack
Reverse Polish Notation Using Stack
Arithmetic Expressions
Polish Notation
1
01-04-2016
• Polish notation
– Named after Polish mathematician Jan
Lukasiewicz.
– Polish POSTFIX notation
• Refers to the notation in which the operator symbol
is placed after its two operands.
AB+ CD* AB*CD+/
2
01-04-2016
(((A+((B*C)/D))-(E*F))-G)
• Polish
P li h Postfix
P fi form:
f
A B C * D / + E F * - G -
• Polish Prefix form:
– Try it out ….
• Advantages:
– No concept of operator priority.
• Simplifies the expression evaluation rule.
– No need of any parenthesis.
• Hence no ambiguity in the order of evaluation.
– Evaluation can be carried out using a single
scan o
sca over
e tthe
eeexpression
p ess o st
string.
g
• Using stack.
3
01-04-2016
4
01-04-2016
Evaluate: 10 6 3 - * 7 4 + -
Scan string from left to right:
10: push (10) Stack: 10
6: push (6) Stack: 10 6
3: push (3) Stack: 10 6 3
-: y = pop() = 3 Stack: 10 6
x = pop() = 6 Stack: 10
push (x-y) Stack: 10 3
*: y = pop() = 3 Stack: 10
x = pop() = 10 Stack: EMPTY
push (x*y) Stack: 30
7: push (7) Stack: 30 7
4: push (4) Stack: 30 7 4
+: y = pop() = 4 Stack: 30 7
x = pop() = 7 Stack: 30
push (x+y) Stack: 30 11
-: y = pop() = 11 Stack: 30 Final result
x = pop() = 30 Stack: EMPTY in stack
push (x-y) Stack: 19
9
Parenthesis Matching
10
5
01-04-2016
11
6
01-04-2016
13
14
7
01-04-2016
Basic Idea
• Let Q denote an infix expression.
– May contain left and right parentheses.
– Operators are:
• Highest priority: ^ (exponentiation)
• Then: * (multiplication), / (division)
• Then: + (addition), – (subtraction)
– Operators at the same level are evaluated from
left to right.
• In the algorithm to be presented:
– We begin by pushing a ‘(’ in the stack.
– Also add a ‘)’ at the end of Q.
15
16
8
01-04-2016
if (a is ‘)’)
{
Repeatedly
p y p
pop
p from stack and add to P each
operator (on the top of the stack) until a
left parenthesis is encountered;
17
Q: A + (B * C – (D / E ^ F) * G) * H )
Q STACK Output Postfix String P
A ( A
+ ( + A
( ( + ( A
B ( + ( A B
* ( + ( * A B
C ( + ( * A B C
- ( + ( - A B C *
( ( + ( - ( A B C *
D ( + ( - ( A B C * D
/ ( + ( - ( / A B C * D
E ( + ( - ( / A B C * D E
^ ( + ( - ( / ^ A B C * D E
F ( + ( - ( / ^ A B C * D E F
) ( + ( - A B C * D E F ^ /
18
9
01-04-2016
* ( + ( - * A B C * D E F ^ /
G ( + ( - * A B C * D E F ^ / G
) ( + A B C * D E F ^ / G * -
* ( + * A B C * D E F ^ / G * -
H ( + * A B C * D E F ^ / G * - H
) A B C * D E F ^ / G * - H * +
19
20
10
01-04-2016
21
11