在这里,我有一个使用 Stack 将 Infix 转换为 Postfix 的代码
代码编译没有错误,但我的问题是当我输入任何中缀时,例如 A+B,我得到一个没有运算符或括号的 AB 后缀,我无法解决这个问题,我明天要考试,请救救我,告诉我我是什么我在这里失踪了,非常感谢......
#include <iostream>
#include <string.h>
using namespace std;
struct stack
{
int ptr;
char arr[50];
stack()
{
ptr=0;
}
char top()
{
return arr[ptr];
}
void push(char ch)
{
ptr++;
arr[ptr]=ch;
}
void pop()
{
ptr-- ;
}
};
void Convert(char[50],char[50]);
bool IsOperand(char);
bool TakesPrecedence(char,char);
void main()
{
char Reply;
do
{
char Infix[50],Postfix[50]="";
cout<<"Enter an Infix expression: "<<endl;
cin>>Infix;
Convert(Infix,Postfix);
cout<<"The equivalent postfix expression is: "<<endl<<Postfix<<endl;
cout<<endl<<"Do another (y/n)? ";
cin>>Reply;
}
while (Reply =='y');
}
void Convert(char Infix[50],char Postfix[50])
{
stack OperatorStack;
char TopSymbol,Symbol;
int L;
for(unsigned k=0;k<strlen(Infix);k++)
{
Symbol=Infix[k];
if (IsOperand(Symbol))
{
L=strlen(Postfix);
Postfix[L]=Symbol;
Postfix[L+1]='\0';
}
else
{
while ( OperatorStack.ptr && TakesPrecedence(OperatorStack.top(),Symbol))
{
TopSymbol= OperatorStack.top();
OperatorStack.pop();
L=strlen(Postfix);
Postfix[L]=TopSymbol;
Postfix[L+1]='\0';
}
if( OperatorStack.ptr && Symbol==')')
OperatorStack.pop();
else
OperatorStack.push(Symbol);
}
}
while(OperatorStack.ptr)
{
TopSymbol=OperatorStack.top();
OperatorStack.pop();
L=strlen(Postfix);
Postfix[L+1]='\0';
}
}
bool IsOperand(char ch)
{
if((ch >='a' &&ch <= 'z') ||(ch >='A' &&ch <= 'Z')||(ch >='0' &&ch <= '9'))
return true;
else
return false;
}
bool TakesPrecedence(char OperatorA,char OperatorB)
{
if(OperatorA='(')
return false;
else if(OperatorB='(')
return false;
else if(OperatorB=')')
return true;
else if(OperatorA='^' && (OperatorB='^'))
return false;
else if(OperatorA='^')
return true;
else if(OperatorB='^')
return false;
else if(OperatorA='*' || (OperatorA='/'))
return true;
else if(OperatorB='*' || (OperatorB='/'))
return false;
else
return true;
}