int prec(char ch)
{
switch (ch){
case '/':
case '*': return 2;
case '+':
case '-': return 1;
default: return 0;
}
}
void infix_postfix(char infix[], char postfix[], int size)
{
stackType<char, 20> s;
stack<char> s;
int precedence;
int i = 0;
int k = 0;
char ch;
while (i < size)
{
ch = infix[i];
//push the open parenthesis
if(ch =='(')
{
s.Push(ch);
i++;
continue;
}
//if a closed parenthesis is encountered, then pop all the elements and append it to the postfix expression till we encounter an open parenthesis
if(ch == ')')
{
while(!s.isEmpty() && s.Top() != '(')
{
postfix[k++] = s.Top();
s.pop();
}
if (!s.isEmpty())
{
s.pop();
}
i++;
continue;
}
precedence = prec(ch);
//If we encounter an operand then append it to the postfix expression
if (precedence = 0)
{
postfix[k++] = ch;
}
else
if(s.isEmpty())
{
//push the operator onto the stack if stack is empty
s.Push(ch);
}
else
{
//pop all the operators from the stack and append it to the postfix expression till we see an operator with a lower precedence of the current operator
while(!s.isEmpty() && s.Top() != '(' && precedence < prec(s.Top()))
{
postfix[k++] = s.Top();
s.pop();
}
s.Push(ch);
}
i++;
}
if(ch == ')')
//if a closed parenthesis is encountered, then pop all the elements and append it to the postfix expression till we encounter an open parenthesis
{
while(!s.isEmpty() && s.Top() != '(')
{
postfix[k++] = s.Top();
s.pop();
}
if (!s.isEmpty())
{
s.pop();
}
i++;
continue;
}
while (!s.isEmpty())
{
postfix[k++] = s.Top();
s.pop();
}
s.Push(ch);
postfix[k] = 0;
}
int main()
{
char infix[] = "a*(b+c)";
int size = strlen(infix);
char postfix[size];
infix_postfix(infix, postfix, size);
cout << "Infix Expression is: " << infix << endl;
cout << "Postfix Expression is: " << postfix;
cout << endl;
return 0;
}
当我执行此代码时,它没有正确地以正确的顺序放置字母和运算符。似乎操作符首先而不是操作数,当我在中缀表达式的中间放置一个左括号时,顺序会更改。例如,当我将+(b + c)作为中缀表达式时,结果以+ cb + a结束。