数据结构表达式求值代码
时间: 2023-11-12 11:56:25 浏览: 115
对于数据结构表达式求值的代码,可以使用栈来实现。以下是一个简单的示例代码:
```
def evaluate_expression(expression):
stack = []
for char in expression:
if char.isdigit():
stack.append(int(char))
else:
operand2 = stack.pop()
operand1 = stack.pop()
if char == '+':
result = operand1 + operand2
elif char == '-':
result = operand1 - operand2
elif char == '*':
result = operand1 * operand2
elif char == '/':
result = operand1 / operand2
stack.append(result)
return stack.pop()
# 测试代码
expression = "(15-2)*3+4/2"
result = evaluate_expression(expression)
print("表达式的求值结果为:", result)
```
阅读全文