思路
变量
String[] arr
Stack
代码
public class Test1 {
public static void main(String[] args) {
String s = "3 40 + 5 * 6 -";
Stack numArr = new Stack(10);
int num1 = 0;
int num2 = 0;
int res = 0;
int index = 0;
String[] arr = s.split(" ");
for(String e:arr) {
System.out.print(e);
}
System.out.println();
while(true) {
if(index >= arr.length) {
break;
}
if(arr[index].matches("\\d+")) {
numArr.push(Integer.parseInt(arr[index]));
}else {
num1 = numArr.pop();
num2 = numArr.pop();
String c = arr[index];
res = numArr.cal(num1,num2,c);
numArr.push(res);
}
index++;
}
res = numArr.pop();
System.out.println(res);
}
}
class Stack{
private int top = -1;
private int[] arr;
private int maxsize;
public Stack(int nums) {
arr = new int[nums];
this.maxsize = nums;
}
//栈空
public boolean isEmpty() {
return this.top == -1;
}
//栈满
public boolean isFull() {
return this.top == this.maxsize - 1;
}
//压栈
public void push(int val) {
if(isFull()) {
System.out.print("栈满!");
return;
}
top++;
arr[top] = val;
}
//弹栈
public int pop() {
if(isEmpty()) {
System.out.print("栈空!");
return -1;
}
int val = arr[top];
top--;
return val;
}
public void show() {
if(isEmpty()) {
System.out.print("栈空!");
return;
}
for(int i = top; i >= 0; i--) {
System.out.println(arr[i]);
}
}
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
public int prior(int i) {
if(i == '+' || i == '-') {
return 0;
}else if(i == '*' || i == '/') {
return 1;
}else {
return -1;
}
}
//查看栈顶元素
public int peak() {
return arr[top];
}
//运算符
public boolean isOper(String c) {
return c == "+" || c == "-" || c == "*" || c == "/";
}
//计算
public int cal(int num1, int num2, String c) {
int res = 0;
switch(c) {
case "+":
res = num1 + num2;
break;
case "-":
res = num2 - num1;
break;
case "*":
res = num2 * num1;
break;
case "/":
res = num2 / num1;
break;
default:
break;
}
return res;
}
}