逆波兰式:中缀表达式,后缀表达式等内容可百度查看。

运算表达式  2+3*(1+2)-6/3

开两个栈,一个存数字,一个存符号。

当 遇到这种情况1:需要先计算后面的内容,再回来计算前面的运算

让符号进栈暂时保存。

还有一种情况2:遇到左括号时,只能进栈等待右括号的到来。右括号到来时,运算整个括号内的内容。


其他情况,都可直接计算。


【代码】

#include<bits/stdc++.h>
using namespace std;
void cal(stack<int> &S1,stack<char> &S2)//进行一次运算
{
    int b=S1.top();S1.pop();
    int a=S1.top();S1.pop();
    char ch=S2.top();S2.pop();
    int ans;
    if(ch=='+')ans=a+b;
    if(ch=='-')ans=a-b;
    if(ch=='*')ans=a*b;
    if(ch=='/')ans=a/b;
    S1.push(ans);
}
bool compare(char l,char r)//l<r  return 1 入栈
{
    if(l=='('||r=='(')return 1;
    if((l=='+'||l=='-')&&(r=='*'||r=='/'))
        return 1;
    return 0;
}
int main()
{
    cout<<"输入表达式:\n";
    string s; cin>>s;
    stack<int>S1;
    stack<char>S2;
    for(int i=0;i<s.length();i++)
    {
        int x=0,flag=0;
        while(s[i]>='0'&&s[i]<='9')
            x=x*10+s[i++]-'0',flag=1;
        if(flag) S1.push(x);
        if(i>=s.length())break;
        if(s[i]==')')//遇 ) 则运算整个括号
        {
            while(S2.top()!='(')
                cal(S1,S2);
            S2.pop();
        }
        else
        {
            while((!S2.empty())&&(!compare(S2.top(),s[i])))//计算
                cal(S1,S2);
            S2.push(s[i]);
        }
    }
    while(!S2.empty())//栈中剩余运算符运算
        cal(S1,S2);
    cout<<S1.top()<<endl;
}