首页 > 试题广场 >

存在中缀表达式:(2*(3-4))*5,通过下面的代码将其转

[单选题]
存在中缀表达式:(2*(3-4))*5,通过下面的代码将其转换为后缀表达式,则当扫描到字符4时,栈ops中所存元素为()
 /**
    * 将中缀表达式转换为后缀表达式
    * @param s 中缀表达式
    * @return String字符串 后缀表达式
    */
    private String postfix(String s){
        // 后缀表达式
        StringBuilder sb = new StringBuilder();
        Stack<Character> ops = new Stack<>();
        int i = 0;
        while(i < s.length()){
            char c = s.charAt(i++);
            if (c == '(' || c == '+' || c == '-' || c == '*'){
                // 加一个空格是为了将操作数之间隔开
                sb.append(" ");
                pushOP(sb,c,ops);
                continue;
            }
            if (c == ')'){
                // 弹出操作符直到(
                while(ops.peek() != '('){
                    sb.append(ops.pop());
                }
                ops.pop();
                continue;
            }
            sb.append(c);
        }
        // 弹出栈中元素
        while(!ops.isEmpty()){
            sb.append(ops.pop());
        }
        return sb.toString();
    }
    private void pushOP(StringBuilder sb,char op,Stack<Character> ops){
        // 栈空,或者栈顶元素为(,操作符直接放入栈中
        if (ops.isEmpty() || ops.peek() == '(' || op == '('){
            ops.add(op);
            return;
        }
        char c = ops.peek();
        // 栈顶操作符的优先级低于当前操作符,直接压入栈中
        if (c != '*' && op == '*'){
            ops.add(op);
            return;
        }
        // 否则,弹出栈顶元素,继续比较
        c = ops.pop();
        sb.append(c);
        pushOP(sb,op,ops);
    }
  • (*
  • (*(-
  • ((-
  • *(
扫描到看成扫描第4个了
发表于 2025-02-27 11:02:36 回复(0)
1. 分析中缀表达式 (2*(3-4))*5 的扫描过程: - 初始时,栈 ops 为空。 - 扫描到 ( ,根据 pushOP 方法逻辑,因为栈空,所以将 ( 压入栈 ops ,此时栈 ops 为 ( 。 - 扫描到 2 ,直接添加到后缀表达式 sb 中,此时 sb 为 2 ,栈 ops 仍为 ( 。 - 扫描到 * ,由于栈顶元素为 ( ,根据 pushOP 方法,将 * 压入栈 ops ,此时栈 ops 为 (* 。 - 扫描到 ( ,将 ( 压入栈 ops ,此时栈 ops 为 ((* 。 - 扫描到 3 ,添加到 sb 中, sb 变为 2 3 ,栈 ops 不变。 - 扫描到 - ,因为栈顶元素为 ( ,将 - 压入栈 ops ,此时栈 ops 为 ((*(- 。 - 扫描到 4 ,此时栈 ops 中所存元素为 ((*(- 。 2. 确定答案: - 答案是B。 当扫描到字符 4 时,栈 ops 中的元素为 ((*(- 。
发表于 2024-11-13 16:10:09 回复(1)
*被pop()了,答案有问题
发表于 2025-10-25 12:08:24 回复(1)