1、编制一个中间代码生成程序,能将算术表达式等翻译成逆波兰形式;
2、程序具有通用性,即能接受各种不同的算术表达式等语法成分。
3、对于语法正确的算术表达式,能生成逆波兰表示,并输出结果;
C++实现如下:
#include<bits/stdc++.h>
using namespace std;
char st[1000]; //保存符号的堆栈数组
int top=-1; //堆栈指针
string ss=""; //保存结果逆波兰式
int main(){
printf("%s","Input:");
string s;
cin>>s;
int L=s.length();
for(int i=0;i<L;i++){
if(s[i]=='+'||s[i]=='-'){
if(top==-1){
st[++top]=s[i];
}
else{
while(st[top]!='('&&top>-1){//遇到 +、- 将栈中元素出栈直到遇见"("或堆栈为空
ss.push_back(st[top]);
top--;
}
st[++top]=s[i]; //再将 +、- 入栈
}
}
else if(s[i]=='*'||s[i]=='/'){
if(top==-1){
st[++top]=s[i];
}
else{
while(st[top]!='('&&(st[top]=='*'||st[top]=='/')){ //遇到 *、/ 将栈中 *、/出栈直到遇见"("或堆栈为空
ss.push_back(st[top]);
top--;
}
st[++top]=s[i]; //再将 *、/ 入栈
}
}
else if(s[i]=='('){ //遇到 "(" 直接入栈
st[++top]=s[i];
}
else if(s[i]==')'){ //遇到右括号将左括号之前全部出栈,加入逆波兰式
while(st[top]!='('){
ss.push_back(st[top]);
top--;
}
top--; //左括号出栈但不加入逆波兰式
}
else{
ss.push_back(s[i]); //操作数直接加入逆波兰式
}
}
//最后,将堆栈中全部元素加入逆波兰式
while(top>-1){
ss.push_back(st[top]);
top--;
}
printf("%s","逆波兰式为:");
cout<<ss<<endl;
return 0;
}