CS212 Sep2016 07 InPostPreExpressions
CS212 Sep2016 07 InPostPreExpressions
Data Structures
and Algorithms (CS212)
Section 07 :
Infix , Prefix and Postfix
Expressions
Eng. Mahmoud Osama Radwan
[email protected] – AAST CCIT
Infix , Prefix , Postfix Expressions
Infix : <operand> <operator> <operand>
Prefix: <operator> <operand> <operand>
Postfix: <operand> <operand> <operator>
Infix Prefix Postfix
2+3 +23 23+
p-q -pq pq-
a+b*c +a*bc abc*+
Infix is human readable.
Prefix & Postfix are good for machines.
Infix , Prefix , Postfix Expressions
Example Converting Infix to Prefix
a*b+c*d-e
[(a*b)+(c*d)]-e
[(*ab)+(*cd)]-e
[+*ab*cd]-e
-+*ab*cde
Infix , Prefix , Postfix Expressions
Initialize(s)
s
Evaluate postfix using stack
23*54*+9- (every digit is a single number)
Initialize(s)
For i=1 …. Length(exp) {
if(exp(i) is operand) {
Push(s,exp(i))
}
else if(exp(i) is operator){
Pop(s,x1,empty)
5 Pop(s,x2,empty)
R = Calculate(exp(i),x1,x2)
6 Push(s,R)
s
}
}
Evaluate postfix using stack
23*54*+9- (every digit is a single number)
Initialize(s)
For i=1 …. Length(exp) {
if(exp(i) is operand) {
Push(s,exp(i))
}
else if(exp(i) is operator){
4 Pop(s,x1,empty)
5 Pop(s,x2,empty)
R = Calculate(exp(i),x1,x2)
6 Push(s,R)
s
}
}
Evaluate postfix using stack
23*54*+9- (every digit is a single number)
Initialize(s)
For i=1 …. Length(exp) {
if(exp(i) is operand) {
Push(s,exp(i))
}
else if(exp(i) is operator){
4*5=20 Pop(s,x1,empty)
20 Pop(s,x2,empty)
R = Calculate(exp(i),x1,x2)
6 Push(s,R)
s
}
}
Evaluate postfix using stack
23*54*+9- (every digit is a single number)
Initialize(s)
For i=1 …. Length(exp) {
if(exp(i) is operand) {
Push(s,exp(i))
}
else if(exp(i) is operator){
20+6=26 Pop(s,x1,empty)
Pop(s,x2,empty)
26 R = Calculate(exp(i),x1,x2)
Push(s,R)
s
}
}
Evaluate postfix using stack
23*54*+9- (every digit is a single number)
Initialize(s)
For i=1 …. Length(exp) {
if(exp(i) is operand) {
Push(s,exp(i))
}
else if(exp(i) is operator){
Pop(s,x1,empty)
9 Pop(s,x2,empty)
26 R = Calculate(exp(i),x1,x2)
Push(s,R)
s
}
}
Evaluate postfix using stack
23*54*+9- (every digit is a single number)
Initialize(s)
For i=1 …. Length(exp) {
if(exp(i) is operand) {
Push(s,exp(i))
}
else if(exp(i) is operator){
26-9=17 Pop(s,x1,empty)
Pop(s,x2,empty)
17 R = Calculate(exp(i),x1,x2)
Push(s,R)
s
}
}
Evaluate postfix using stack
23*54*+9- (every digit is a single number)