我有这个程序用于中缀到后缀表达式的转换,但它不能正常工作......例如。如果我输入表达式a+b+(c-d)*e
,它会给出输出后缀表达式,abcd-++e*
而不是abcd-e*++
.
char inputexp[50], stacks[50], resultexp[50];
int stacktop=-1, resulttop=-1;
void priority()
{
'^'>'/'>'*'>'+'>'-';
}
void push(char a)
{
stacktop++;
stacks[stacktop]=a;
}
void pop()
{
resulttop++;
resultexp[resulttop]=stacks[stacktop];
--stacktop;
}
void input()
{
cout<<"Enter the infix expression=";
scanf("%s", inputexp);
}
void operandadd (char a)
{
resulttop++;
resultexp[resulttop]=a;
}
void operatorfound (char a)
{
if(stacktop==-1||stacks[stacktop]=='(')
{
push(a);
}
else
{
if(a<stacks[stacktop])
{
while(stacks[stacktop]>a&&stacks[stacktop]!='(')
{
pop();
}
push(a);
}
else
{
push(a);
}
}
}
void rightparenthesisfound (char a)
{
while(stacks[stacktop]!='(')
{
pop();
}
--stacktop;
}
void leftparenthesisfound (char a)
{
push(a);
}
void variablefound(char a)
{
resulttop++;
resultexp[resulttop]=a;
}
void result()
{
cout<<"Postfix Expression:"<<endl;
for(int i=0; i<strlen(resultexp); i++)
{
cout<<resultexp[i]<<endl;
}
}
int main()
{
input();
cout<<strlen(inputexp)<<endl;
priority();
for(int i=0; i<strlen(inputexp); i++)
{
if(inputexp[i]=='+'||inputexp[i]=='-'||inputexp[i]=='*'||inputexp[i]=='/'||inputexp[i]=='^')
{
operatorfound(inputexp[i]);
cout<<stacks<<endl;
}
else if(inputexp[i]=='(')
{
leftparenthesisfound(inputexp[i]);
}
else if(inputexp[i]==')')
{
cout<<"RIGHT "<<"STACK:"<<stacks<<endl;
rightparenthesisfound(inputexp[i]);
cout<<"RIGHT PARENTHESIS FOUND:"<<" Stack: "<<stacks<<"\t"<<"Result:"<<resultexp;
}
else
{
variablefound(inputexp[i]);
cout<<"RESULT: "<<resultexp<<endl;
}
}
if(stacktop!=-1)
{
while(stacktop!=-1)
{
pop();
}
}
cout<<endl<<resultexp<<endl;
return 0;
}