Week3 -Stack Infix to Postfix
Week3 -Stack Infix to Postfix
operator operator
follows precedes
operands operands
a+b ab+
a+b*c
Postfix Expression
a+b ab+
a+b*c abc*+
(a+b)*c
Postfix Expression
a+b ab+
a+b*c abc*+
(a+b)*c ab+c*
(a-b)*(c+d)
Postfix Expression
a+b ab+
a+b*c abc*+
(a+b)*c ab+c*
(a-b)*(c+d) ab-cd+*
Postfix Expression
6 3 +2*=
Postfix Expression Evaluation
6 3 +2*=
Read the operands until find the
operators
Perform the operation
Continue the process
Postfix Expression Evaluation
6 3 +2*=
Stack
Postfix Expression Evaluation
6 3 +2*=
Push 6
Stack
Postfix Expression Evaluation
6 3 +2*=
Push 6
Push 3 3
Stack
Postfix Expression Evaluation
6 3 +2*=
Push 6
Push 3 3
6
Operator find
Stack
Postfix Expression Evaluation
6 3 +2*=
Push 6
Push 3
Operator find : operator = +
Pop stack twice : Op2 = 3,Op1 = 6
Stack
Postfix Expression Evaluation
6 3 +2*=
Push 6
Push 3
Operator find .operator = +
Pop stack twice. Op2 = 3,Op1 = 6
Op1+op2=9
Stack
Postfix Expression Evaluation
6 3 +2*=
Push 6
Push 3
Operator find .operator = +
Pop stack twice. Op2 = 3,Op1 = 6
Op1+op2=9 9
Push 9
Stack
Postfix Expression Evaluation
6 3 +2*=
Push 6
Push 3
Operator find .operator = +
Pop stack twice. Op2 = 3,Op1 = 6
Op1+op2=9
Push 9 2
Push 2 9
Op2*op1=18
Stack
Push 18
Operator find =
Postfix Expression Evaluation
6 3 +2*=
Push 6
Push 3
Operator find .+
Pop stack twice. Op2 = 3,Op1 = 6
Op1+op2=9
Push 9
Push 2
Operator find. *
Pop stack twice. Op2 = 2,Op1 = 9
18
Op2*op1=18
Push 18 Stack
Operator find =
Pop
Algorithm
3+2*5=
(4+5)/(6*2)=
Input File
#6 #3 + #2 * =
Every operand first has # .
Main Algorithm
(A + B) * (C - D)
Final Expression : AB + CD -*
CS2143 Data Structures
Balancing Symbols