CSC2100B - Biola University
Download
Report
Transcript CSC2100B - Biola University
Infix to postfix conversion
Process the tokens from a vector infixVect of tokens (strings) of an infix expression one by one
When the token is an operand
Add it to the end of the vector postfixVect of token (strings) that is used to store the
corresponding postfix expression
When the token is a left or right parenthesis or an operator
If the token x is “(“
if the token x is “)”
Push the token x onto the stack
Repeatedly pop a token y from the stack and push_back that token y to
postfixVect until “(“ is encountered in the end of the stack. Pop “(“ from the
stack.
If the stack is already empty before finding a “(“, this expression is not a valid
infix expression.
if the token x is a regular operator
Step 1: Check the token y currently on the top of the stack.
Step 2:
If (i) the stack is not empty, (ii) y is not “(“
and (iii) y is an operator of
higher or equal precedence than that of x,
then: pop the token y from the stack and push_back the token y to postfixVect,
and repeat Step 1 again
else: push the token x onto the stack.
When all tokens in infixVect are processed as described above, repeatedly pop a token y from
the stack and push_back that token y to postfixVect until the stack is empty.
Infix to postfix conversion
infixVect
(1+2–3)*4–(5+6)
postfixVect
Infix to postfix conversion
stack
infixVect
(1+2–3)*4–(5+6)
postfixVect
(
Infix to postfix conversion
stack
infixVect
(1+2–3)*4–(5+6)
postfixVect
1
(
Infix to postfix conversion
stack
infixVect
(1+2–3)*4–(5+6)
postfixVect
1
+
(
Infix to postfix conversion
stack
infixVect
(1+2–3)*4–(5+6)
postfixVect
12
+
(
Infix to postfix conversion
stack
infixVect
(1+2–3)*4–(5+6)
postfixVect
12+
-
(
Infix to postfix conversion
stack
infixVect
(1+2–3)*4–(5+6)
postfixVect
12+3
-
(
Infix to postfix conversion
stack
infixVect
(1+2–3)*4–(5+6)
postfixVect
12+3-
Infix to postfix conversion
stack
infixVect
( 1 + 2 – 3 ) *4 – ( 5 + 6 )
postfixVect
12+3-
*
Infix to postfix conversion
stack
infixVect
( 1 + 2 – 3 ) * 4– ( 5 + 6 )
postfixVect
12+3-4
*
Infix to postfix conversion
stack
infixVect
( 1 + 2 – 3 ) * 4 –( 5 + 6 )
postfixVect
12+3–4*
-
Infix to postfix conversion
stack
infixVect
( 1 + 2 – 3 ) * 4 – (5 + 6 )
postfixVect
12+3–4*
(
-
Infix to postfix conversion
stack
infixVect
(1+2–3)*4–(5+6)
postfixVect
12+3–4*5
(
-
Infix to postfix conversion
stack
infixVect
( 1 + 2 – 3 ) * 4 – ( 5 +6 )
postfixVect
+
(
-
12+3–4*5
Infix to postfix conversion
stack
infixVect
( 1 + 2 – 3 ) * 4 – ( 5 + 6)
postfixVect
+
(
-
12+3–4*56
Infix to postfix conversion
stack
infixVect
(1+2–3)*4–(5+6)
postfixVect
12+3–4*56+
-
Infix to postfix conversion
stack
infixVect
(1+2–3)*4–(5+6)
postfixVect
12+3–4*56+–