中序表达式转后序

中序表达式转后序表达式的方法

  1. 遍历表达式,数字入后序表达式栈; “(”入符号栈
  2. 遇到 “)”;则符号栈不断弹出运算符,直到弹出 “)”
  3. 遇到运算符,则与符号栈栈顶运算符比较优先级,若栈顶优先级较大,则将栈顶运算符弹出并推入后序栈;否则直接推入符号栈
  4. 后序栈弹出并反转即为后序表达式
//方便起见,将后序栈改为后序队列
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.util.Stack;

public class InfixToPostfix {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		String str = input.next();
		Stack<Character> op = new Stack<>();
		Queue<Character> postfix = new LinkedList<>();
		for(int i = 0; i < str.length(); i++) {
			char ch = str.charAt(i);
			if(ch >= '0' && ch <= '9')
				postfix.add(ch);
			else if(ch == '(')
				op.push(ch);
			else if(ch == ')') {
				while((ch = op.pop()) != '(') {
					postfix.add(ch);
					if(op.empty())
						break;
				}
			}
			else {
				if(!op.empty()) {
					char top = op.peek();
					if((top == '+' || top == '-' ) && (ch == '*' || ch == '/'))
						op.push(ch);
					else {
						while(ch != '(' && top != '(' && !op.empty())
							postfix.add(op.pop());
						op.push(ch);
					}
				}else
					op.push(ch);
			}
		}
		while(!op.empty())
			postfix.add(op.pop());
		while(!postfix.isEmpty())
			System.out.print(postfix.poll());
	}
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
中序表达式是指运算符位于两个操作数之间的表达式,例如:3 + 4 * 2。而后序表达式是指运算符位于操作数之后的表达式,例如:3 4 2 * +。 实现从中序表达式后序表达式换可以使用栈来实现。具体步骤如下: 1. 创建一个空栈和一个空列表,用于存储后序表达式。 2. 从左到右扫描中序表达式的每个字符,如果是数字则添加到后序表达式列表中;如果是运算符,则进行如下操作: 1. 如果运算符优先级比栈顶运算符优先级高,或者栈为空,则将运算符入栈。 2. 否则,将栈顶运算符弹出并添加到后序表达式列表中,直到栈顶运算符优先级比当前运算符低或者栈为空,然后将当前运算符入栈。 3. 扫描完中序表达式后,将栈中所有运算符弹出并添加到后序表达式列表中。 4. 返回后序表达式列表。 下面是实现代码: ```python def infix_to_postfix(infix_expr): precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3} stack = [] postfix_expr = [] for token in infix_expr: if token.isdigit(): postfix_expr.append(token) elif token in precedence: while stack and precedence[token] <= precedence.get(stack[-1], 0): postfix_expr.append(stack.pop()) stack.append(token) elif token == '(': stack.append(token) elif token == ')': while stack and stack[-1] != '(': postfix_expr.append(stack.pop()) stack.pop() while stack: postfix_expr.append(stack.pop()) return postfix_expr ``` 使用示例: ```python infix_expr = '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3' postfix_expr = infix_to_postfix(infix_expr.split()) print(' '.join(postfix_expr)) # 输出:3 4 2 * 1 5 - 2 3 ^ ^ / + ``` 分析: 时间复杂度为 O(n),其中 n 是中序表达式的长度。算法的空间复杂度为 O(n),主要是由栈和后序表达式列表所占用的空间引起的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值