表达式求值 stl容器 栈和队列的应用

#include <iostream>
#include <vector>
#include <algorithm>
#include <stack>
#include <queue>
#include <string>
#include <map>
using namespace std;
struct Node{
    
    
    int  num;
    char op;
    int  flag;//flag指示是数字还是符号,为0表示数字为1表示符号
};
stack<Node> t;//栈:用于转后缀时的符号栈和计算值时的数字栈
queue<Node> q;//记录后缀表达式
map<char,int> m;//用于指示操作符的优先级
Node node;
int main()
{
    
    
    ios::sync_with_stdio(false);
    cin.tie(0);
    m['+'] = 1; m['-'] = 1;
    m['*'] = 2; m['/'] = 2;
    int i,j,n,l,r;
    cin>>n;
    string str;
    char op;
    for(i = 0 ;i < n ;i++)
    {
    
    
        while(!t.empty()) t.pop();
        while(!q.empty()) q.pop();
        cin>>str;
        for(j = 0 ;j < (int)str.length() ; )
        {
    
    
            if(str[j]>='0'&&str[j]<='9')
            {
    
    
                node.flag = 0;
                node.num  = str[j++] - '0';
                while(str[j]>='0'&&str[j]<='9')
                {
    
    
                    node.num = node.num*10+str[j] - '0';
                    j++;
                }
                q.push(node);
            }else{
    
    
                node.flag = 1;
                node.op   = str[j];
                if(str[j] == '(')
                {
    
    
                    t.push(node);
                }else if(str[j] == ')'){
    
    
                    while(t.top().op!='(')
                    {
    
    
                        q.push(t.top());
                        t.pop();
                    }
                    t.pop();
                }else{
    
    
                    while(!t.empty()&&m[str[j]]<=m[t.top().op])
                    {
    
    
                        q.push(t.top());
                        t.pop();
                    }
                    t.push(node);
                }
                j++;
            }
        }
        while(!t.empty())
        {
    
    
            q.push(t.top());
            t.pop();
        }
        //此时的q已经存好了后缀表达式
        while(!q.empty())
        {
    
    
            if(q.front().flag == 0)
            {
    
    
                t.push(q.front());
                q.pop();
            }else if(q.front().flag == 1){
    
    
                r = t.top().num;
                t.pop();
                l = t.top().num;
                t.pop();
                op = q.front().op;
                if(op == '+') node.num = l+r;
                else if(op == '-') node.num = l-r;
                else if(op == '*') node.num = l*r;
                else if(op == '/') node.num = l/r;
                t.push(node);
                q.pop();
            }
        }
        cout<<t.top().num<<endl;
    }
    return 0;
}

可用此段代码查看后缀表达式:

while(!q.empty())
        {
    
    
            if(q.front().flag == 0)
                cout<<q.front().num;
            else
                cout<<q.front().op;
            q.pop();
        }

猜你喜欢

转载自blog.csdn.net/weixin_44142774/article/details/113704457