#include <iostream>
#include <stack>
#include <string>

using namespace std;

int main()
{
    stack<char> t;
    string s;
    string res;
    cin >> s;
    for (int i = 0; i < s.size(); i++)
    {
        if (s[i] == '+' || s[i] == '-')
        {
            while (!t.empty() && t.top() != '(')
            {
                res.append(1, t.top());
                t.pop();
            }
            t.push(s[i]);
        }
        else if (s[i] == '*' || s[i] == '/')
        {
            while (!t.empty() && t.top() != '('  && t.top() != '+' && t.top() != '-')
            {
                res.append(1, t.top());
                t.pop();
            }
            t.push(s[i]);
        }
        else if (s[i] == '(')
        {
            t.push(s[i]);
        }
        else if (s[i] == ')')
        {
            while (t.top() != '(')
            {
                res.append(1, t.top());
                t.pop();
            }
            t.pop(); // 将(出栈
        }
        else
        {
            res.append(1, s[i]);
        }
    }

    while (!t.empty())
    {
        res.append(1, t.top());
        t.pop();
    }
    cout << res;

    return 0;
}
#include <iostream>
#include <stack>
#include <string>

using namespace std;
int main()
{
    int ctmp;
    stack<int> s;
    string s1;
    char c;
    while (cin >> c && c != '#')
    {
        s1.append(1, c);
    }
    s1.append(1, '#');
    for (int i = 0; i < s1.size()-1; i++)
    {
        if (s1[i] >= '0' && s1[i] <= '9')
        {
            if (!s.empty())
            {
                ctmp = s.top();  //保留倒数第二个
            }
            s.push(s1[i] - '0');
        }
        else if (s1[i] == '+')
        {
            int res = ctmp + s.top();
            s.pop();
            s.pop();
            if (!s.empty())
            {
                ctmp = s.top();  //保留倒数第二个
            }
            s.push(res);
        }
        else if (s1[i] == '-')
        {
            int res = ctmp - s.top();
            s.pop();
            s.pop();
            if (!s.empty())
            {
                ctmp = s.top();  //保留倒数第二个
            }
            s.push(res);
        }
        else if (s1[i] == '*')
        {
            int res = ctmp * s.top();
            s.pop();
            s.pop();
            if (!s.empty())
            {
                ctmp = s.top();  //保留倒数第二个
            }
            s.push(res);
        }
        else if (s1[i] == '/')
        {
            int res = ctmp / s.top();
            s.pop();
            s.pop();
            if (!s.empty())
            {
                ctmp = s.top();  //保留倒数第二个
            }
            s.push(res);
        }
        else
        {
            break;
        }
    }
    cout << s.top();
    return 0;
}
最后修改:2019 年 04 月 10 日
如果觉得我的文章对你有用,请随意赞赏