zoukankan      html  css  js  c++  java
  • 栈在表达式求值中的应用

    将中缀表达式转成后缀表达式。

    #include<iostream>
    #include <stack>
    #include<map>
    #include <math.h>
    #include <stdlib.h>
    #include <string.h>
    #include <stdio.h>
    
    using namespace std;
    //把中缀表达式转化为后缀表达式  a+b-a*((c+d)/e-f)+g#    1+2-3*((4+5)/3-6)+7#e
    int Complete(int a,int b,char c){
        if(c=='+'){
            return a+b;
        }else if(c=='-'){
            return a-b;
        }else if(c=='*'){
            return a*b;
        }else
           return a/b;
    }
    //void InitS()
    int main(){
        map<char,int> ispM;
        map<char,int> icpM;
        stack<int> s1;
        stack<char> s2;
        char res[20];
        ispM['#']=0;ispM['(']=1;ispM['*']=ispM['/']=5;ispM['+']=ispM['-']=3;ispM[')']=6;
        icpM['#']=0;icpM['(']=6;icpM['*']=icpM['/']=4;icpM['+']=icpM['-']=2;icpM[')']=1;
    
        s2.push('#');
        char c;
         //InitS();
         int coun=0;
        memset(res,0,sizeof(res));
        while(scanf("%c",&c)!=EOF){
                if(c=='e') {
                    break;
                }
            if(c>='0'&&c<='9'){
                res[coun++]=c;
              //  cout<<c;
            }else{
                if(ispM[s2.top()]>icpM[c]){
                while(ispM[s2.top()]>icpM[c]){
                    res[coun++]=s2.top();
                    s2.pop();
                }
                }
                if(ispM[s2.top()]<icpM[c]){
                    s2.push(c);
                }
    
                if(ispM[s2.top()]==icpM[c]){
                    s2.pop();
                }
            }
        }
        for(int i=0;i<coun;i++){
            if(res[i]>='0'&&res[i]<='9'){
                s1.push(res[i]-'0');
            }else  {
                int t1=s1.top();
                s1.pop();
                int t2=s1.top();
                s1.pop();
                int newdata=Complete(t2,t1,res[i]);
                s1.push(newdata);
            }
        }
        cout<<s1.top()<<endl;
        s1.pop();
    
    
        return 0;
    }
    
  • 相关阅读:
    2021.2.6 日记
    P2168 荷马史诗
    2021寒假集训——数论初步
    2021.2.5 日记
    2021.2.4 日记
    2021.2.3 日记
    堆——学习笔记
    树状数组——学习笔记
    Easy | LeetCode 350. 两个数组的交集 II | 哈希 | 排序+双指针
    Easy | LeetCode 66. 加一 | 模拟
  • 原文地址:https://www.cnblogs.com/wintersong/p/5727103.html
Copyright © 2011-2022 走看看