中缀表达式转换成后缀
时间: 2024-06-14 20:03:53 浏览: 101
以下是中缀表达式转换成后缀的过程:
```python
def infix_to_postfix(infix):
precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3}
stack = []
postfix = ''
for char in infix:
if char.isalnum():
postfix += char
elif char == '(':
stack.append(char)
elif char == ')':
while stack and stack[-1] != '(':
postfix += stack.pop()
stack.pop()
else:
while stack and stack[-1] != '(' and precedence[stack[-1]] >= precedence[char]:
postfix += stack.pop()
stack.append(char)
while stack:
postfix += stack.pop()
return postfix
infix_expression = "1+((2+3)*4)-5"
print("Infix Expression:", infix_expression)
print("Postfix Expression:", infix_to_postfix(infix_expression)) # 输出:123+4*+5-
```
阅读全文