中缀表达式转后缀表达式

来源:互联网 发布:linux curl 命令 post 编辑:程序博客网 时间:2024/06/17 21:44

算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。日常使用的算术表达式是采用中缀表示法,即二元运算符位于两个运算数中间。请设计程序将中缀表达式转换为后缀表达式。

输入格式说明:

输入在一行中给出不含空格的中缀表达式,可包含+、-、*、\以及左右括号(),表达式不超过20个字符。

输出格式说明:

在一行中输出转换后的后缀表达式,要求不同对象(运算数、运算符号)之间以空格分隔,但结尾不得有多余空格。

样例输入与输出:

序号输入输出1

2+3*(7-4)+8/4
2 3 7 4 - * + 8 4 / +
2
((2+3)*4-(8+2))/5
2 3 + 4 * 8 2 + - 5 /
3
1314+25.5*12
1314 25.5 12 * +
4
-2*(+3)
-2 3 *
5
123
123
考虑到输出是以空格间隔的字符串,使用一个vector<string>存储结果。

维护一个栈。遍历输入字符串s的字符,若s[i]是数字,检测连续的数字字符串,存入结果数组。

若s[i]是字符,判断s[i]与栈顶字符的优先级:

若s[i]是左括号,直接入栈;

若s[i]是右括号,依次将栈顶的加减乘除号弹出存入结果数组,最后弹出左括号;

若s[i]为乘除号,将栈顶的乘除号弹出并存入结果数组,最后s[i]入栈;

若s[i]是加减号,依次将栈顶的加减乘除号弹出并存入结果数组,最后s[i]入栈。

需要注意加号与正号的区分,负号与减号的区分。

/*2015.8.8cyq*/#include <iostream>#include <stack>#include <string>#include <vector>#include <fstream>using namespace std;//ifstream fin("case5.txt");//#define cin finint main(){string s;cin>>s;int n=s.size();stack<char> stk;vector<string> result;int i=0;string tmp;bool flag=true;while(i!=n){if(s[i]=='('){//左括号,入栈stk.push(s[i]);i++;}else if(s[i]==')'){//右括号,处理到左括号位置,存入结果数组while(stk.top()!='('){tmp=stk.top();result.push_back(tmp);stk.pop();}stk.pop();i++;}else if(s[i]=='*'||s[i]=='/'){if(stk.empty()||stk.top()=='('||stk.top()=='+'||stk.top()=='-'){stk.push(s[i]);i++;}else{tmp=stk.top();result.push_back(tmp);stk.pop();stk.push(s[i]);i++;}}else if(s[i]=='+'){if(i==0||s[i-1]=='(')//正号,而不是加号,直接忽略i++;else{while(!stk.empty()&&stk.top()!='('){tmp=stk.top();result.push_back(tmp);stk.pop();}stk.push(s[i]);i++;}}else if(s[i]=='-'){if(i==0||s[i-1]=='('){//负号,而不是减号flag=false;i++;}else{while(!stk.empty()&&stk.top()!='('){tmp=stk.top();result.push_back(tmp);stk.pop();}stk.push(s[i]);i++;}}else{//数字,直接存入结果数组tmp.clear();if(!flag){flag=true;tmp+="-";}while(i<n&&(s[i]>='0'&&s[i]<='9'||s[i]=='.')){tmp+=s[i];i++;}result.push_back(tmp);}}while(!stk.empty()){tmp=stk.top();stk.pop();result.push_back(tmp);}int len=result.size();if(len>0)cout<<result[0];for(int i=1;i<len;i++){cout<<" "<<result[i];}return 0;}



0 0