这里要注意各个输入的情况,有正负数,和小数的存在,但题目上没写,这是最烦的。
排序的关键是运算符的优先级问题,以及正负数中的符号与加减号如何区别。还有内括号的先运算。
下面是代码:
#include<iostream>
using namespace std;
#include<stack>
int main()
{
string arr;
cin >> arr;
stack<char> a;
stack<char>c;
int i = 0;
bool flag = true; //用于判断邻接前面是否已经出现了运算符,如果出现了那这个就是正负号
char b,result[200];
while (i<arr.size())
{
switch (arr.at(i))
{
case '+':
if (flag)
{
flag = false;
i++;
break;
}
else
{
if (!c.empty())
{
b = c.top();
if (b == '*' || b == '/')
{
while (!c.empty()&&b!='(') //注意不能将栈中的'('号也输出了。
{
a.push(b);
a.push(' ');
c.pop();
if (!c.empty())
b = c.top();
}
}
}
}
c.push(arr.at(i));
i++;
break;
case'-':
if (flag)
{
a.push(arr.at(i));
flag = false;
i++;
break;
}
else
{
if (!c.empty())//判断栈是否为空
{
b = c.top();
if (b == '*' || b == '/')
{
while (!c.empty() && b != '(') //同上
{
a.push(b);
a.push(' ');
c.pop();
if (!c.empty())
b = c.top();
}
}
}
}
c.push(arr.at(i));
i++;
break;
case '*':
c.push(arr.at(i));
flag = true;
i++;
break;
case '/':
c.push(arr.at(i));
flag = true;
i++;
break;
case'(':
c.push(arr.at(i));
i++;
break;
case ')':
if (!c.empty())
{
b = c.top();
if (b != '(')
{
while (b != '(')
{
a.push(b);
a.push(' ');
c.pop();
if (!c.empty())
b = c.top();
else
break;
}
}
}
c.pop();
i++;
break;
default:
while (arr.at(i) >= '0' && arr.at(i) <= '9')
{
a.push(arr[i]);
i++;
if (arr[i] == '.')
{
a.push(arr[i]);
i++;
}
if (i >= arr.size())
break;
}
a.push(' ');
flag = false;
break;
}
}
if (!c.empty())
{
b = c.top();
while (!c.empty())
{
if (b == '(')
c.pop();
else
{
a.push(b);
a.push(' ');
c.pop();
}
if (!c.empty())
b = c.top();
}
}
int k = 0;
while (!a.empty())
{
b = a.top();
a.pop();
result[k] = b;
k++;
}
for (int j = k-1; j>0; j--) //逆序输出
cout <<result[j];
}
运行结果:
惯例,以上均本人愚见,不喜勿喷。
如有优化请留言,我会及时回复。