-
Infix - Postfix
Code:
switch (input[i])
{
case '(':
operator_stack.push(input[i]);
break;
case '+':
case '-':
case '*':
case '/':
case '^':
if (operator_stack.empty())
operator_stack.push(input[i]);
else
{
int operator_precedence = 0;
int top_operator_precedence = 0;
if (input[i] == '^' )
operator_precedence = 3;
if (input[i] == '*' || input[i] == '/')
operator_precedence = 2;
if (input[i] == '+' || input[i] == '-')
operator_precedence = 1;
if (operator_stack.top() == '^' )
top_operator_precedence = 3;
if (operator_stack.top() == '*' || operator_stack.top() == '/')
top_operator_precedence = 2;
if (operator_stack.top() == '+' || operator_stack.top() == '-')
top_operator_precedence = 1;
if (operator_precedence >= top_operator_precedence)
operator_stack.push (input[i]);
else
value_stack.push (input[i]);
}
break;
case ')':
while (operator_stack.top() != '(' )
{
value_stack.push (operator_stack.top());
operator_stack.pop();
}
break;
default:
value_stack.push (input[i]);
The logic here is wrong, when I try the example from wikipedia 3+4*2/(1−5)^2^3
I keep geting 34215-23^^(/*+ insetad of 342*15-23^^/+
Where did I go wrong ?
-
Code:
if (operator_precedence >= top_operator_precedence)
operator_stack.push (input[i]);
else
value_stack.push (input[i]);
^^ Has issues
-
Start with the simple test 3+4+5
Also - do you remove '(' from the original stack when the ')' is encountered?