import java.util.ArrayList;
import java.util.List;
public class Calculator {
public static void main(String[] args) {
// String suffixExpression = "3 4 + 5 * 6 -"; //测试结果为29,正确
// String suffixExpression = "30 4 + 5 * 6 -"; //测试结果为164,正确
String suffixExpression = "4 5 * 8 - 60 + 8 2 / +"; //测试结果为76,正确
List<String> list = getListString(suffixExpression);
int result = calculate(list);
System.out.println("计算结果 = " + result);
}
public static List<String> getListString(String suffixExpression) {
String[] split = suffixExpression.split(" ");
List<String> list = new ArrayList<>();
for (String item : split) {
list.add(item);
}
return list;
}
public static int calculate(List<String> list) {
ArrayStack stack = new ArrayStack(10);
for (String item : list) {
if (item.matches("\\d+")) {
stack.push(Integer.parseInt(item));
} else {
int num1 = stack.pop();
int num2 = stack.pop();
int res = 0;
if ("+".equals(item)) {
res = num1 + num2;
} else if ("-".equals(item)) {
res = num2 - num1;
} else if ("*".equals(item)) {
res = num1 * num2;
} else if ("/".equals(item)) {
res = num2 / num1;
} else {
throw new RuntimeException("运算符号有误~");
}
stack.push(res);
}
}
return stack.peek();
}
}
class ArrayStack {
public int maxSize;
public int[] stack;
public int top = -1;
public ArrayStack(int maxSize) {
this.maxSize = maxSize;
stack = new int[maxSize];
}
public boolean isFull() {
return top == maxSize - 1;
}
public boolean isEmpty() {
return top == -1;
}
public int peek() {
if (isEmpty()) {
throw new RuntimeException("栈空~");
}
return stack[top];
}
public void push(int value) {
if (isFull()) {
System.out.println("栈满");
return;
}
stack[++top] = value;
}
public int pop() {
if (isEmpty()) {
throw new RuntimeException("栈空~");
}
return stack[top--];
}
public void show() {
if (isEmpty()) {
System.out.println("栈空~");
return;
}
for (int i = top; i >= 0; i--) {
System.out.printf("stack[%d]=%d\n", i, stack[i]);
}
}
}
逆波兰计算器的实现
最新推荐文章于 2021-10-20 10:31:03 发布