java 中缀表达式到后缀表达式的转换。

8 篇文章 0 订阅
  • 算法思想
    数字直接加入后缀表达式
    运算符时:
    a.若为’(’,入栈;
    b.若为’)’,则依次把栈中的运算符加入后缀表达式,直到出现’(’,并从栈中删除’)’;
    c.若为’+’,’-’,’*’,’/’,
     ·栈空,入栈;
     ·栈顶元素为’(’,入栈;
     ·高于栈顶元素优先级,入栈;
     ·否则,依次弹出栈顶运算符,直到一个优先级比它低的运算符或’('为止;
    d.遍历完成,若栈非空依次弹出所有元素。

  • 代码

import java.util.Scanner;
import java.util.Stack;

class Test {
    public static void main(String[] args) {
        String expression = "";
        Scanner input = new Scanner(System.in);
        expression = input.nextLine();
        input.close();
        System.out.println(change(expression));
    }

    public static String change(String expression) {
        String postfixExpression = "";                                  // 记录后缀表达式
        Stack<String> symbolStack = new Stack<>();                      // 符号栈
        String[] expressionList = expression.split(" ");                // 根据空格拆分存放在数组中
        for (String str : expressionList) {
            if (!isOperator(str)) {                                     // 不是操作符时
                postfixExpression += (str + " ");                       // 记录
                continue;
            }
            if (symbolStack.empty()||str.equals("(")) {                 // 开始时栈为空时 或者 遇到"("
                symbolStack.push(str);
                continue;
            }
            if (str.equals(")")) {                                      // 遇到")"
                while (true) {                                          // 不为空
                    if (symbolStack.peek().equals("(")) {               // 如果遇到左括号的时候退出循环
                        symbolStack.pop();
                        break;
                    }
                    postfixExpression += (symbolStack.pop() + " ");     // 记录
                }                                                       // 将当前符号入栈
                continue;
            }
            if (!comp(symbolStack.peek(), str)) {                       // 判断是否出栈
                while (!symbolStack.empty()) {                          // 不为空
                    if (symbolStack.peek().equals("("))                 // 如果遇到左括号的时候退出循环
                        break;
                    postfixExpression += (symbolStack.pop() + " ");     // 记录
                }
            }
            symbolStack.push(str);                                      // 将当前符号入栈
        }
        while (!symbolStack.empty())                                    // 最后将剩余的出栈
            postfixExpression += (symbolStack.pop() + " ");
        return postfixExpression.trim();
    }

    public static boolean isOperator(String str) {                      // 是否为操作符
        String[] operator = { "+", "-", "*", "/", "(", ")" };
        for (String ope : operator) {
            if (str.equals(ope))
                return true;
        }
        return false;
    }

    public static boolean comp(String str1, String str2) {              // 判断操作符str2优先级是否比str1大
        char c1 = str1.charAt(0);
        char c2 = str2.charAt(0);
        char[] operator = "+-*/".toCharArray();
        int n1 = -1, n2 = -1;
        for (int i = 0; i < operator.length; i++) {
            if (operator[i] == c1)
                n1 = i;
            if (operator[i] == c2)
                n2 = i;
        }
        return n2 / 2 > n1 / 2;
    }
}

例:输入:a + b * c + ( d * e + f ) * g
结果为:a b c * + d e * f + g * +

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中缀表达式后缀表达式的方法如下: ```java import java.util.Stack; public class InfixToPostfix { public static String infixToPostfix(String infix) { Stack<Character> stack = new Stack<>(); StringBuilder postfix = new StringBuilder(); for (int i = 0; i < infix.length(); i++) { char c = infix.charAt(i); if (Character.isDigit(c)) { postfix.append(c); } else if (c == '(') { stack.push(c); } else if (c == ')') { while (!stack.isEmpty() && stack.peek() != '(') { postfix.append(stack.pop()); } stack.pop(); } else { while (!stack.isEmpty() && precedence(c) <= precedence(stack.peek())) { postfix.append(stack.pop()); } stack.push(c); } } while (!stack.isEmpty()) { postfix.append(stack.pop()); } return postfix.toString(); } private static int precedence(char operator) { switch (operator) { case '+': case '-': return 1; case '*': case '/': return 2; case '^': return 3; default: return -1; } } } ``` 其中,`infixToPostfix`方法接收一个中缀表达式字符串,返回一个后缀表达式字符串。该方法使用了栈来实现中缀表达式后缀表达式的过程,具体实现过程如下: 1. 遍历中缀表达式字符串中的每个字符。 2. 如果当前字符是数字,则直接将其添加到后缀表达式字符串中。 3. 如果当前字符是左括号,则将其压入栈中。 4. 如果当前字符是右括号,则将栈中的元素弹出并添加到后缀表达式字符串中,直到遇到左括号为止。 5. 如果当前字符是运算符,则将栈中的元素弹出并添加到后缀表达式字符串中,直到栈为空或栈顶元素为左括号或栈顶运算符优先级低于当前运算符,然后将当前运算符压入栈中。 6. 遍历完中缀表达式字符串后,将栈中剩余的元素弹出并添加到后缀表达式字符串中。 7. 返回后缀表达式字符串。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值