Converting Infix to Postfix
typedef fsu::Queue < token > tokenQueue;
typedef fsu::Stack < token > tokenStack;
int i2p (tokenQueue & Q1, tokenQueue & Q2)
// converts infix expression in Q1 to postfix expression in Q2
{
tokenStack S;
Q2.Clear();
while (!Q1.Empty())
{
if (Q1.Front() == '(')
// push '(' to mark beginning of a parenthesized expression
{
S.Push(Q1.Front());
Q1.Pop();
}
else if (Q1.Front().Operator())
{
// pop previous operators of equal or higher precedence to output
while (!S.Empty() && S.Top() >= Q1.Front())
{
Q2.Push(S.Top());
S.Pop();
}
// then push new operator onto stack
S.Push(Q1.Front());
Q1.Pop();
}
else if (Q1.Front() == ')')
// regurgitate operators for the parenthesized expression
{
while (!S.Empty() && !(S.Top() == '('))
{
Q2.Push(S.Top());
S.Pop();
}
if (S.Empty()) // unbalanced parentheses
{
cout << "** error: too many right parens\n";
return 0;
}
S.Pop(); // discard '('
Q1.Pop(); // discard ')'
}
else // t should be an operand
// send operand directly to output
{
Q2.Push(Q1.Front());
Q1.Pop();
}
} // end while()
// regurgitate remaining operators
while (!S.Empty())
{
if (S.Top() == '(') // unbalanced parentheses
{
cout << "** error: too many left parens\n";
return 0;
}
Q2.Push(S.Top());
S.Pop();
}
return 1;
} // end i2p()