集册 Java实例教程 将表达式转换为后缀

将表达式转换为后缀

欢马劈雪     最近更新时间:2020-01-02 10:19:05

481
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
将表达式转换为后缀

import java.util.HashMap;

import java.util.Map;

import java.util.Stack;

/*
来 自*
 n  o  w  j  a  v  a . c o m
*/

public class Main {


  private static String convertToPostfix(String expr) {

    Map<Character, Integer> opPrecedence = new HashMap<>();

    opPrecedence.put('+', 0);

    opPrecedence.put('-', 0);

    opPrecedence.put('*', 1);

    opPrecedence.put('/', 1);


    Stack<Character> stack = new Stack<>();

    String output = "";


    int i = 0;

    while (i < expr.length()) {

      char cur = expr.charAt(i);/*时   代    Java - nowjava.com 提供*/


      if (cur == ' ') {

        ++i;

        continue;

      }


      if (Character.isDigit(cur)) {

        String numStr = "";


        while (i < expr.length() && Character.isDigit(expr.charAt(i))) {

          numStr += expr.charAt(i);

          ++i;

        }


        output += numStr;

        output += ' ';


        continue;

      }


      if (cur == '(') {

        stack.push(cur);


        ++i;


        continue;

      }


      if (cur == ')') {

        while (!stack.empty() && stack.peek() != '(') {

          output += stack.pop();

          output += ' ';

        }


        if (stack.empty()) {

          throw new IllegalArgumentException("Invalid expression");

        }


        stack.pop();


        ++i;


        continue;

      }


      if (cur == '+' || cur == '-' || cur == '*' || cur == '/') {

        while (!stack.empty() && opPrecedence.containsKey(stack.peek())

            && opPrecedence.get(stack.peek()) >= opPrecedence.get(cur)) {

          output += stack.pop();

          output += ' ';

        }


        stack.push(cur);


        ++i;


        continue;

      }


      throw new IllegalArgumentException("Invalid expression");

    }


    while (!stack.empty()) {

      if (stack.peek() == 
展开阅读全文