zoukankan      html  css  js  c++  java
  • 栈的应用--中序表达式转后序表达式

    栈的应用--中序表达式转后序表达式


    infix : a+b*c+(d*e+f)*g
    postfix : abc*+de*f+g*+

    有以下四种情况:

    1. 操作数->直接输出
    2. 操作符->将栈顶输出,直到栈顶优先级小于该操作符,最后把该操作符压入栈
    3. '(' ->入栈
    4. ')' ->将栈中在'('之后的操作符全部输出
    #include <iostream>
    #include <stack>
    #include <map>
    #include <string>
    
    using namespace std;
    
    int main() {
      stack<char> op;
      
      // 规定优先级
      map<char, int> mymap;
      mymap['+'] = 1;
      mymap['*'] = 2;
    
      string infix = "a+b*c+(d*e+f)*g";
      string postfix = "";
    
      for (int i = 0; i < infix.length(); i++) {
        // 操作数->直接输出
        if (infix[i] >= 'a' && infix[i] <= 'z') {
          postfix += infix[i];
        } else if (infix[i] == '(') {
          // '(' ->入栈
          op.push(infix[i]);
        } else if (infix[i] == ')') {
          // ')' ->将栈中在'('之后的操作符全部输出
          while (op.top() != '(') {
    	    postfix += op.top();
    		op.pop();
          }
          // 将'('弹出
          op.pop();
        } else {
          // 操作符->将栈顶输出,直到栈顶优先级小于该操作符,最后把该操作符压入栈
          while (!op.empty() && mymap[op.top()] >= mymap[infix[i]]) {
    		postfix += op.top();
    		op.pop();
          }
          op.push(infix[i]);
        }
      }
      // 将栈中剩余的操作符输出
      while (!op.empty()) {
        postfix += op.top();
        op.pop();
      }
    
      cout << postfix << endl;
    
      return 0;
    }
    
    
  • 相关阅读:
    13 内建属性 _getattribute_ 内建函数
    12 垃圾回收GC
    11 元类
    12 动态语言 __slots__
    11 作用域
    10 带参数的装饰器 通用装饰器 类装饰器
    9 装饰器
    8 闭包
    6 生成器 yield 协程
    cmd常用命令
  • 原文地址:https://www.cnblogs.com/bgmind/p/3989808.html
Copyright © 2011-2022 走看看