zoukankan      html  css  js  c++  java
  • 表达式计算

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

    思路:数字栈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;
    }
  • 相关阅读:
    java中的堆、栈、常量池
    java中int和Integer的区别
    python linecache模块读取文件的方法
    Python 字符串中 startswith()方法
    Python中的filter()函数的用法
    python sort、sorted高级排序技巧
    二级指针内存模型(一)
    Linux下多线程模拟停车场停车
    linux线程操作
    C语言实现多线程排序
  • 原文地址:https://www.cnblogs.com/GeekZRF/p/6675190.html
Copyright © 2011-2022 走看看