数据结构中缀表达式转化为后缀表达式代码
时间: 2024-11-03 13:19:17 浏览: 38
中缀表达式(如 `A + B * C`)转换成后缀表达式(也称为逆波兰表示法,如 `ABC+*`),通常涉及到两个步骤:先扫描并堆叠运算符,然后按序输出操作数。这里是一个简单的Python代码示例,使用了栈的数据结构:
```python
def infix_to_postfix(expression):
precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3} # 运算符优先级
output = [] # 后缀表达式的堆栈
operator_stack = [] # 运算符堆栈
tokens = expression.split() # 将字符串分解为单词列表
for token in tokens:
if token.isdigit(): # 如果是数字,直接添加到输出
output.append(token)
elif token in ['+', '-', '*', '/', '^']: # 如果是运算符
while (operator_stack and
operator_stack[-1] != '(' and
precedence[token] <= precedence[operator_stack[-1]]):
output.append(operator_stack.pop())
operator_stack.append(token)
elif token == ')': # 遇到右括号,将左括号和其中的内容全部压回
while operator_stack[-1] != '(':
output.append(operator_stack.pop())
operator_stack.pop() # 移除左括号
# 将剩余运算符压入输出
while operator_stack:
output.append(operator_stack.pop())
return ' '.join(output) # 用空格连接生成的后缀表达式
# 示例
expression = "A+B*C"
postfix_expression = infix_to_postfix(expression)
print(f"原表达式:{expression}")
print(f"后缀表达式:{postfix_expression}")
```
阅读全文
相关推荐











