void Expression::convertInfixToPostfix()
{
/*Define operator stack*/
string postfix;
int size = infixExpression.size();
stackType<char> s(size);
s.initializeStack();
for (int iter = 0; iter < size; ++iter)
{
switch (infixExpression[iter])
{
case'+':
case'-':
case'/':
case'*':
if (s.empty())
s.push(infixExpression[iter]);
else
/*if precedence of current operator is higher than
one on top of the stack, we simply push the current
operator to the top of the stack*/
if (precedence(s, infixExpression[iter]))
s.push(infixExpression[iter]);
else
{
/*Pop from the stack and append it to string stream.
Repeat it unless we find an operator on top of the stack
whose precedence is lower or stack is empty.*/
do
{
postfix += s.top();
s.pop();
}while (!s.empty() && !precedence(s, infixExpression[iter]) && s.top() != '(');
/*Now push the current operator to the stack*/
s.push(infixExpression[iter]);
}
break;
case'(':
s.push(infixExpression[iter]);
break;
case')':
while(s.top() != '(')
{
postfix += s.top();
s.pop();
}
s.pop();
break;
default:
if (isOperand(infixExpression[iter]))
postfix+= infixExpression[iter];
break;
}
/*Pop one by one from operator stack and append it to our stream*/
while(!s.empty())
{
postfix += s.top();
s.pop();
}
}
postfixExpression = postfix;
}
bool Expression::precedence(stackType<char> s, char operator_specified)
{
char top_operator = s.top();
if ((top_operator != '(' && (operator_specified == '+') || (operator_specified == '-')))
returnfalse;
if ((top_operator == '+') || (top_operator == '-') || (top_operator == '('))
returntrue;
elsereturnfalse;
}
bool Expression::isOperand(char symbol)
{
switch (symbol) {
case'+':
case'-':
case'*':
case'/':
case'(':
case')':
case';':
returnfalse;
default:
returntrue;
}
}