一、实现思路
1、将字符串切割,并用一个字符串数组接收
2、索引从右到左开始扫描
3、如果为数字则入栈,为运算符就将数栈弹出两个数字进行运算,将结果压入栈
4、重复2、3,直至到左边边界
二、代码实现
import java.util.Stack;
public class PolishDemo {
public static boolean recognize(char ch) {
return ch == '*' || ch == '+' || ch == '-' || ch == '/';
}
public static int operateNum(int num1, int num2, char ch) {
int res = 0;
switch (ch) {
case '+':
res = num1 + num2;
break;
case '-':
res = num1 - num2;
break;
case '*':
res = num1 * num2;
break;
case '/':
res = num1 / num2;
break;
default:
System.out.println("无法识别符号");
}
return res;
}
public static void main(String[] args) {
Stack<String> valueStack = new Stack<String>();
//输入字符串
// Scanner sc = new Scanner(System.in);
// String s = sc.nextLine();
String s = "- 1 + 2 3";
String[] list = s.split(" ");
String str = "";
int length = list.length;
for (int i = length -1; i >= 0; i--) {
str = list[i];
if(str.length() != 1){//这个一定为多位数,直接入栈
valueStack.push(str);
}else {//判断是运算符还是数字
if(recognize(str.charAt(0))){//如果为运算符
int num1 = Integer.parseInt(valueStack.pop());
int num2 = Integer.parseInt(valueStack.pop());
valueStack.push(String.valueOf(operateNum(num1, num2, str.charAt(0))));
}else {//如果为数字
valueStack.push(str);
}
}
}
System.out.println("数据栈的个数=" + valueStack.size());
System.out.printf("%s=%s", s, valueStack.pop());
}
}
如有错误欢迎指正