ArrayStack 代码来自
public class PolandNotation {
public static void main(String[] args) {
System.out.println(calculate("4 5 * 8 - 60 + 8 2 / +"));
System.out.println(calculate2(list2PolandList(expression2List("1+((2+3)*4)-5"))));
System.out.println(calculate2(list2PolandList(expression2List("7*2-2-5+10-5+8/4"))));
}
public static int calculate(String expression) {
String[] s = expression.split(" ");
ArrayStack arrayStack = new ArrayStack(10);
for (String s1 : s) {
if (ArrayStack.isOper(s1.charAt(0))) {
int num1 = arrayStack.pop();
int num2 = arrayStack.pop();
int calc = ArrayStack.calc(num1, num2, s1.charAt(0));
arrayStack.push(calc);
} else {
arrayStack.push(Integer.parseInt(s1));
}
}
return arrayStack.pop();
}
public static int calculate2(List<String> list) {
ArrayStack arrayStack = new ArrayStack(10);
for (String s1 : list) {
if (ArrayStack.isOper(s1.charAt(0))) {
int num1 = arrayStack.pop();
int num2 = arrayStack.pop();
int calc = ArrayStack.calc(num1, num2, s1.charAt(0));
arrayStack.push(calc);
} else {
arrayStack.push(Integer.parseInt(s1));
}
}
return arrayStack.pop();
}
public static List<String> expression2List(String expression) {
List<String> list = new ArrayList<>();
int i = 0;
String str = "";
char c;
do {
if (expression.charAt(i) < 48 || expression.charAt(i) > 57) {
list.add("" + expression.charAt(i));
i++;
} else {
while (i < expression.length() && expression.charAt(i) >= 48 && expression.charAt(i) <= 57) {
str += expression.charAt(i);
i++;
}
list.add(str);
str = "";
}
} while (i < expression.length());
return list;
}
public static List<String> list2PolandList(List<String> list) {
ArrayStack2 stack = new ArrayStack2(10);
List<String> polandList = new ArrayList<>();
for (String s : list) {
if (s.matches("\\d+")) {
polandList.add(s);
} else if ("(".equals(s)) {
stack.push(s.charAt(0));
} else if (")".equals(s)) {
while (!"(".equals(String.valueOf(stack.peek()))) {
polandList.add(String.valueOf(stack.pop()));
}
stack.pop();
} else {
while (stack.getTop() >= 0 && ArrayStack.getPriority(stack.peek()) >= ArrayStack.getPriority(s.charAt(0))) {
polandList.add(String.valueOf(stack.pop()));
}
stack.push(s.charAt(0));
}
}
while (stack.getTop() >= 0) {
polandList.add(String.valueOf(stack.pop()));
}
return polandList;
}
}
|