转换要按照运算符优先级。
(s) 为中缀表达式,(sta) 为转换中维护的一个栈,(a) 为最终的后缀表达式。
顺序扫描一遍中缀表达式。如果遇到数,直接加入到后缀表达式中;如遇到操作符:
-
栈为空,直接将该操作符入栈。
-
否则,一直弹栈,直到栈顶操作符优先级更低(更低指严格更低,优先级相同的也要弹栈)
从栈内弹出的元素直接加入到后缀表达式中。
最后扫描完后需要把栈内的元素弹出。
for(int i=1;i<=n;i++){
if('0'<=s[i]&&s[i]<='9')
a[++m]=s[i];
if(s[i]=='^') sta[++top]=s[i];
if(s[i]=='*'||s[i]=='/'){
while(sta[top]=='^'||sta[top]=='*'||sta[top]=='/')
a[++m]=sta[top--];
sta[++top]=s[i];
}
if(s[i]=='+'||s[i]=='-'){
while(sta[top]=='^'||sta[top]=='*'||sta[top]=='/'||sta[top]=='+'||sta[top]=='-')
a[++m]=sta[top--];
sta[++top]=s[i];
}
if(s[i]=='(') sta[++top]='(';
if(s[i]==')'){
while(sta[top]!='(')
a[++m]=sta[top--];
top--;
}
}
while(top) a[++m]=sta[top--];
for(int i=1;i<=m;i++) printf("%c ",a[i]);