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


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


    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;
    }
    
    
  • 相关阅读:
    电磁学10.安培环路定律
    电磁学9.毕奥-萨法尔定律与高斯磁定理
    电磁学8.磁场中的运动电荷
    C语言-指针
    Windows和Linux的简单对比
    电磁学7.磁场与洛伦兹力
    睡眠呼吸机-呼吸触发相关算法
    电磁学6.电流与电动势
    code的用法
    字符串处理
  • 原文地址:https://www.cnblogs.com/bgmind/p/3989808.html
Copyright © 2020-2023  润新知