算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。日常使用的算术表达式是采用中缀表示法,即二元运算符位于两个运算数中间。请设计程序将中缀表达式转换为后缀表达式。
输入格式说明:
输入在一行中给出不含空格的中缀表达式,可包含+、-、*、\以及左右括号(),表达式不超过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 |
1. 若是数字则直接放到输出;
2. 若是操作符‘+’/‘-’/’*‘/’、’, 则放入一个运算符堆栈,放入之前判断当前运算符优先级是否大于栈顶运算符,是则直接压入,不是则将栈顶元素出栈放入输出中,指到当前运算符优先级大于栈顶元素或栈为空后,讲当前运算符入栈;这里要注意,‘+’、-、符号若是前面不是运算因子,则只是作为正负数的标识,并不是运算符;
3. 若是‘(’,则直接入栈,入栈后‘(’的优先级降至最低;
4. 若是‘)’, 将栈顶元素出栈放入输出中,指到遇到栈顶元素为‘(’为止;
5. 输入全部读完后,若是栈中还有元素,全部出栈病放入输出中。
源代码:
#include<iostream>
#include<stack>
#include<string>
#include<iterator>
#include<cctype>
using namespace std;
int main()
{
string in,out;
char curr, fore=-1, next;
string::iterator iter;
stack<char> stk;
cin >> in;
for(iter=in.begin(); iter!=in.end(); iter++)
{
curr = *iter;
/*if it is a digit, add to the output immediately*/
if((curr>='0'&& curr<='9') || curr=='.')
{
out.push_back(curr);
if((iter+1)==in.end() || (!isdigit(*(iter+1))&& *(iter+1)!='.')) //pay attention that '.' is a part of number
out.push_back(' ');
}
else if(curr == '+' || curr == '-')
{
if(fore == '(' || fore == -1) //if '+'/'-' add befor a number ,and the fore is not a compute factor, it indicate a number is negative or not
if(curr == '+')
continue;
else
out.push_back(curr);
else
{
if(stk.empty())
stk.push(curr);
else if(stk.top() != '(')
{
while(!stk.empty() && stk.top() != '(')
{
out.push_back(stk.top());
out.push_back(' ');
stk.pop();
}
stk.push(curr);
}
else
stk.push(curr);
}
}
else if(curr == '*' ||curr == '/')
{
if(stk.empty() || stk.top() != '*' ||stk.top() != '/')
{
stk.push(curr);
}
else
{
while(!stk.empty() && (stk.top() == '*' || stk.top() =='/'))
{
out.push_back(stk.top());
out.push_back(' ');
stk.pop();
}
stk.push(curr);
}
}
else if(curr == '(')
{
stk.push(curr);
}
else if(curr == ')')
{
while(stk.top() != '(')
{
out.push_back(stk.top());
out.push_back(' ');
stk.pop();
}
stk.pop();
}
fore = curr;
}
while(!stk.empty())
{
out.push_back(stk.top());
out.push_back(' ');
stk.pop();
}
for(iter=out.begin(); iter!=(out.end()-1); iter++)
cout<< *iter;
cout<<endl;
return 0;
}