使用JAVA实现逆波表示
时间: 2023-05-31 21:03:48 浏览: 51
逆波兰表示(Reverse Polish Notation,RPN)是一种数学表达式的表示方法,它可以避免使用括号,并且可以很容易地在计算机中实现。在逆波兰表示中,运算符在操作数的后面,而不是在操作数的中间。
以下是使用JAVA实现逆波兰表示的示例代码:
```java
import java.util.Stack;
public class ReversePolishNotation {
public static void main(String[] args) {
String[] tokens = {"2", "1", "+", "3", "*"};
int result = evalRPN(tokens);
System.out.println(result);
}
public static int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for (String token : tokens) {
if (token.equals("+")) {
int num2 = stack.pop();
int num1 = stack.pop();
stack.push(num1 + num2);
} else if (token.equals("-")) {
int num2 = stack.pop();
int num1 = stack.pop();
stack.push(num1 - num2);
} else if (token.equals("*")) {
int num2 = stack.pop();
int num1 = stack.pop();
stack.push(num1 * num2);
} else if (token.equals("/")) {
int num2 = stack.pop();
int num1 = stack.pop();
stack.push(num1 / num2);
} else {
stack.push(Integer.parseInt(token));
}
}
return stack.pop();
}
}
```
在这个示例代码中,我们使用一个栈来存储操作数。遍历表达式中的每个元素,如果是一个操作符,则从栈中弹出两个操作数,执行相应的操作,并将结果压入栈中。如果是一个操作数,则将其转换为整数并压入栈中。最后,栈中的唯一元素就是表达式的结果。