![]() |
School of Engineering and
Applied
Science Department of Computer Science CSci 133 -- Algorithms and Data Structures I http://www.seas.gwu.edu/~csci133/spring04 Prof. Michael B. Feldman mfeldman@gwu.edu |
Figure 1. Simple Infix-to-RPN Translation |
![]() |
Convert Expression to RPN (no
operator precedences or parentheses):
{
initialize saved-operator variable and RPN string;}
while (there are tokens remaining in the expression)
{
T = next token from expression;
if (T is a variable or numeric literal)
{
add T to the RPN string;
}
else if (T is '+', '-', '*', or '/')
{
if (we've saved an operator)
{
add saved operator to RPN string
}
save T
}
else
{
report error!
}
}
return RPN string
|
|
![]() |
initialize operator stack and RPN string;}
while (there are tokens remaining in the expression)
{
T = next token from expression;
if (T is a variable or numeric literal)
{
add T to the RPN output string;
}
else if (T is '+', '-', '*', or '/')
{
if ((operator stack is empty) or
(precedence(operator at top of stack) < precedence(T)))
{
push T onto the operator stack;
}
else // clear operator stack and push new one onto it
{
do
{
add the operator at the top of the stack to the RPN string;
pop the stack;
}
while ((the stack is not empty) and
(precedence(T) < precedence(operator at top of stack)));
push T onto the stack;
}
}
else
{
report error!
}
}
// no more tokens left in expression - clear stack into output
while (operator stack is not empty)
{
add the operator at the top of the stack to the RPN string;
pop the stack;
}
return RPN string
|
|
![]() |
Convert Expression to RPN (with
parentheses and precedences):
{
initialize operator stack and RPN string;
while (there are tokens remaining in the expression)
{
T = next token from expression;
if (T == '(')
{
push T onto the stack;
}
else if (T is a variable or numeric literal)
{
add T to the RPN output string;
}
else if (T is '+', '-', '*', or '/')
{
if ((operator stack is empty) or
(the value at the top of the stack is '(') or
(precedence(operator at top of stack) < precedence(T)))
{
push T onto the operator stack;
}
else // clear operator stack and push new token onto it
{
do
{
add the operator at the top of the stack to the RPN string;
pop the stack;
}
while ((the stack is not empty) and
(the top of the stack is not '(') and
(precedence(T) < precedence(operator at top of stack)));
push T onto the stack;
}
else if (T is ')') // clear operator stack back to the '('
{
while (top of operator stack is not '(')
{
add the operator at the top of the stack to the RPN string;
pop the stack;
}
}
else
{
report error!
}
}// no more tokens left in expression - clear stack into output
while (operator stack is not empty)
{
add the operator at the top of the stack to the RPN string;
pop the stack;
}
return RPN string
}
(end of article)