算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。日常使用的算术表达式是采用中缀表示法,即二元运算符位于两个运算数中间。请设计程序将中缀表达式转换为后缀表达式。
输入格式:
输入在一行中给出不含空格的中缀表达式,可包含+、-、*、/以及左右括号(),表达式不超过20个字符。
输出格式:
在一行中输出转换后的后缀表达式,要求不同对象(运算数、运算符号)之间以空格分隔,但结尾不得有多余空格。
输入样例:
2+3*(7-4)+8/4
输出样例:
2 3 7 4 - * + 8 4 / +
#include<iostream>
#include<stack>
using namespace std;
bool yoXji(char s, char s2) {// 传入 栈区
if (s == '(' || s2 == '(') {
return false;
}//为括号加入栈区,不进行输出
if (s == '+' || s == '-') {
return true;
}//传入的为+ - 号
else {//传入的为 * /
if (s2 == '+' || s2 == '-') {
return false;
}//如果后者优先级小 不输出
return true;
}
}
int main() {
string str;//创建字符串类
stack<char> s;
cin >> str;
int IsNegative = 0;
int flag =0;
for (int i = 0; str[i]; i++)
{//处理字符串
/* 第一步处理数字 */
if (isdigit(str[i]))
{
if(flag)
cout << " ";
if (IsNegative)cout << "-";//输出负数
while (isdigit(str[i]) || str[i] == '.')
{
cout << str[i++];
if(!flag)flag=1;
}
i--;
if (IsNegative)
IsNegative = 0;//每次输出完数字默认设置为0
}//是数字 或者是负数
else//处理字符
{ //优先级大于栈顶的入栈,优先级小于的将栈区出栈后入栈
if (i == 0 || !isdigit(str[i - 1])&&str[i-1]!=')')//特殊情况一为负数输出
{
if (str[i] == '-') IsNegative = 1;
else if (str[i] != '+')s.push(str[i]);
}
else {
if (s.empty())
{
s.push(str[i]);//空栈直接入即可
}
else if (str[i] == '(')
{
s.push(str[i]);
}
else if (str[i] == ')')
{
while (!s.empty() && s.top() != '(')
{
cout << " "<< s.top() ;
s.pop();
}
s.pop();
}
else if (str[i] == '+' || str[i] == '-')//是低级运算符或者不进行运算的高级运算符
{
while (!s.empty() && yoXji(str[i], s.top()))
{
cout << " " << s.top() ;
s.pop();
}
s.push(str[i]);
}
else//最高级运算符
{
while (!s.empty() && yoXji(str[i], s.top()))
{
cout << " " << s.top() ;
s.pop();
}
s.push(str[i]);
}
}
}
}
while (!s.empty())
{
cout <<" "<< s.top();
s.pop();
}
return 0;
}