用于在C ++中评估Postfix表示法的程序

假设我们有后缀表达式,并且我们必须评估该值。后缀表达式也称为反向波兰表示法。在这里,我们必须使用堆栈数据结构来解决后缀表达式。

因此,如果表达式为“ 21 + 3 *”,则答案将为9。

让我们看看步骤-

  • 对于后缀表达式中的每个字符ch,请执行

    • 将ch添加到堆栈中

    • :=从堆栈中弹出第一个元素,

    • b:=从堆栈中弹出第二个元素

    • res:= b $\ odot $a

    • 将res推入堆栈

    • 如果ch是运算符$\ odot $,则

    • 否则,如果ch是操作数,则

    • 堆栈顶部的返回元素

    让我们看下面的实现以更好地理解-

    示例

    #include<bits/stdc++.h>
    using namespace std;
    float scanNum(char ch){
       int value;
       value = ch;
       return float(value-'0');//return float from character
    }
    int isOperator(char ch){
       if(ch == '+'|| ch == '-'|| ch == '*'|| ch == '/' || ch == '^')
          return 1;//character is an operator
          return -1;//not an operator
       }
       int isOperand(char ch){
          if(ch >= '0' && ch <= '9')
             return 1;//character is an operand
          return -1;//not an operand
       }
       float operation(int a, int b, char op){
          //执行操作
          if(op == '+')
             return b+a;
          else if(op == '-')
             return b-a;
          else if(op == '*')
             return b*a;
          else if(op == '/')
             return b/a;
          else if(op == '^')
             return pow(b,a); //find b^a
          else
       return INT_MIN; //return negative infinity
    }
    float postfixEval(string postfix){
       int a, b;
       stack<float> stk;
       string::iterator it;
       for(it=postfix.begin(); it!=postfix.end(); it++){
          //读取元素并执行后缀评估
          if(isOperator(*it) != -1){
             a = stk.top();
             stk.pop();
             b = stk.top();
             stk.pop();
             stk.push(operation(a, b, *it));
          }else if(isOperand(*it) > 0){
             stk.push(scanNum(*it));
          }
       }
       return stk.top();
    }
    main(){
       string post = "21+3*";
       cout <<postfixEval(post);
    }

    输入值

    "21+3*"

    输出结果

    9
    猜你喜欢