zoukankan      html  css  js  c++  java
  • 后缀表达式求值

    #include<iostream>
    #include<stack>
    #include<cstring>
    #include<string>
    using namespace std;
    int judge(char popx,char x);
    int func(string String,int *i);
    int calculate(int x,int y,char str); 
    int main()
    {
    int n,i;
    char a[6000];
    stack<char>str;
    str.push('#');
    cin>>n;
    while(n--)
    {
    cin>>a;
    string substr="";
    int j;
    for(i=0;i<strlen(a);)
    {
    if(a[i]-'0'>=0&&a[i]-'0'<=9)
    {
    for(j=i;a[j]-'0'>=0&&a[j]-'0'<=9;j++)
    substr+=a[j];
    substr+=' ';
    i=j;
    }
    else
    {
    if(judge(str.top(),a[i])==1)
    {
    substr+=str.top();
                        str.pop();
    }
    else
    if(judge(str.top(),a[i])==2)
    {
    str.push(a[i]);
    i++;
    }
    else
    if(judge(str.top(),a[i])==3)
    {
    str.pop();
    i++;
    }
    }
    }
    while(str.top()!='#')
    {
    substr+=str.top();
    str.pop();
    }
    stack<int>stack1;
    cout<<substr<<endl;
    for(i=0;i<substr.length();i++)
    {
    int num=0;
    if(substr[i]-'0'>=0&&substr[i]-'0'<=9)
    stack1.push(func(substr,&i));
    else
    {
    int num1=stack1.top();
    stack1.pop();
    int num2=stack1.top();
    stack1.pop();
    stack1.push(calculate(num2,num1,substr[i]));
    }
    }
    cout<<stack1.top()<<endl;
    stack1.pop();
    }
    }
    int judge(char popx,char x)
    {
    if(popx=='*'||popx=='/')
    {
    if(x=='*'||x=='/'||x=='+'||x=='-'||x==')')   //输出 
    return 1;
    else
    if(x=='(')                                //入栈 
    return  2;
    }
    else
    if(popx=='+'||popx=='-')
       {
    if(x=='*'||x=='/'||x=='(')
    return 2;
    else
    if(x=='+'||x=='-'||x==')')
    return 1;
    }
    else
    if(popx=='('&&x!=')')
    return 2;
    else
    if(popx=='('&&x==')')
    return 3;                                         //出栈后移 
    else
    if(popx=='#')
    return 2;
    }


    int calculate(int x,int y,char str)
    {
    if(str=='+')
    return x+y;
    else
    if(str=='-')
    return x-y;
    else
    if(str=='*')
    return x*y;
    else
    if(str=='/')
    return x/y;
    }
    int func(string String,int *i)
    {
    int j,num=0;
    for(j=*i;String[j]-'0'>=0&&String[j]-'0'<=9&&String[j]!=' ';j++)
    {
    num=num*10+(String[j]-'0');
    }
    *i=j;
    return num;
    }
  • 相关阅读:
    sessionid如何产生?由谁产生?保存在哪里?
    springmvc原理
    java基础面试题
    mysql数据库去重复
    git安装和初次使用
    String的按值传递,java传参都是传值
    sublime Text3使用笔记
    git命令使用记录
    Git:错误:error:src refspec master does not match any
    java并发编程实战学习(3)--基础构建模块
  • 原文地址:https://www.cnblogs.com/liguangsunls/p/7365480.html
Copyright © 2011-2022 走看看