按照王道书上的算法
#include<iostream>
#include<string>
#include<stack>
using namespace std;
class Test
{
private:
string str;
stack<char> st;
public:
Test(string str);
string Postfix();
};
int main()
{
while (1) {
string str;
cin >> str;
Test A(str);
cout << A.Postfix() << endl;
}
return 0;
}
Test::Test(string str)
{
this->str = str;
}
string Test::Postfix()
{
char ch;
char old_ch;
string str1;
for (int i = 0; i < str.length(); i++)
{
ch = str[i];
//如果是数字 直接加到字符串中
if (ch <= '9' && ch >= '0') {
str1 += ch;
}
//左括号入栈
if (ch == '(')
{
st.push(ch);
}
//右括号循环出栈,直到遇到左括号
if (ch == ')')
{
while (st.top() != '(')
{
old_ch = st.top();
str1 += old_ch;
st.pop();
}
st.pop();
}
//加减乘除情况
if (ch == '+' || ch == '-' || ch == '*' || ch == '/')
{
str1 += '#';//分割数字
//加减为最低优先级,直接出栈就可以
if (ch == '+' || ch == '-') {
while (!st.empty()){
old_ch = st.top();
if (old_ch == '(')
{
break;
}
st.pop();
str1 += old_ch;
}
st.push(ch);
}
//乘除
else {
while (!st.empty())
{
old_ch = st.top();
if (old_ch == '(')
{
break;
}
//乘除只有遇到乘除才可以直接出栈
if (old_ch == '*' || old_ch == '/') {
st.pop();
str1 += old_ch;
}
else {
break;
}
}
st.push(ch);
}
}
}
while (!st.empty())
{
str1 += st.top();
st.pop();
}
return str1;
}