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;
}