这个算法有一个前提,那就是操作数是正整数且其十进制形式不超过2位,运算符只有加减乘除
代码如下:
//用于判断运算符优先级的高低,优先级高于或等于就返回true,否则为false
bool Priority(char a,char b)
{
if((a=='+'||a=='-')&&(b=='+'||b=='-'||b=='*'||b=='/'))
{
return true;
}
else if((a=='*'||a=='/')&&(b=='*'||b=='/'))
{
return true;
}
return false;
}
//将中缀表达式转化为后缀表达式:
void ChangeToRPN(ElemType str[],int length,ElemType* &str1) //RPN指逆波兰式,也就是后缀表达式
{
int j=0;
str1=(char*)malloc(sizeof(char)*MaxSize); //str1是字符数组,用于存放处理后的后缀表达式
memset(str1,' ',MaxSize);
ElemType topElem;
SqStack S; //定义一个栈
InitStack(S); //初始化栈
for(int i=0;i<length;i++)
{
if(str[i]>='0'&&str[i]<='9') //遇到操作数
{
str1[j]=str[i];
str[i+1]>='0'&&str[i+1]<='9'?j++:j=j+2;
}
else if(str[i]=='+'||str[i]=='-'||str[i]=='*'||str[i]=='/') //遇到运算符
{
while(GetTop(S,topElem)&&topElem!='('&&Priority(str[i],topElem))
{ //Priority是用于判断运算符优先级的自定义函数
Pop(S,topElem);
str1[j]=topElem;
j=j+2;
}
Push(S,str[i]);
}
else if(str[i]==')') //遇到右括号
{
while(GetTop(S,topElem))
{
Pop(S,topElem);
if(topElem=='(')break;
str1[j]=topElem;
j=j+2;
}
}
else if(!Push(S,str[i]))printf("Your input is too long!!\n"); //这句纯粹是为了鲁棒性,如果遇到左括号的话
}
//将栈中剩下的运算符弹出
while(Pop(S,topElem)){
str1[j]=topElem;
j=j+2;
}
return;
}