表达式计算

计算一个包含+ - * / ( ) 的合法表达式的值

思路:数字栈num,运算符栈op。当前操作符优先级不大于栈顶操作符优先级,则数字栈num和运算符栈op出栈,处理后的数字和当前运算符继续与栈顶操作符比较,直至当前运算符的优先级大于栈顶,处理后的数字和当前运算符入栈。

代码:

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<map>
#include<queue>
#include<stack>
using namespace std;
const int maxn=1000;
stack<int>num;
stack<char>op;
char s[maxn];
map<char,int>sign;
void init(int n)
{
    s[n]='#';
    while(!num.empty()) num.pop();
    while(!op.empty()) op.pop();
    op.push('#');
}
int main()
{
    sign['#']=0;
    sign['(']=sign[')']=1;
    sign['+']=sign['-']=2;
    sign['*']=sign['/']=3;
    scanf("%s",s);
    int n=strlen(s);
    init(n);
    int x=0;
    for(int i=0; i<=n; i++)
    {
        if('0'<=s[i]&&s[i]<='9') x=x*10+(s[i]-'0');
        else if(s[i]=='(') op.push(s[i]);
        else
        {
            while(sign[op.top()]>=sign[s[i]])
            {
                char f=op.top(); op.pop();
                if(f=='('&&s[i++]==')') continue;
                if(f=='#'&&s[i]=='#') break;
                int fig=num.top(); num.pop();
                //cout<<fig<<" "<<f<<" "<<x<<" ";
                if(f=='+') x=fig+x;
                else if(f=='-') x=fig-x;
                else if(f=='*') x=fig*x;
                else if(f=='/') x=fig/x;
                //cout<<x<<endl;
            }
            num.push(x);
            op.push(s[i]);
            x=0;
        }
    }
    cout<<num.top()<<endl;
    return 0;
}
原文地址:https://www.cnblogs.com/GeekZRF/p/6675190.html