一、使用栈完成对表达式计算的思路
1.首先我们需要两个栈,一个是数栈用于存放数,另一个是符号栈用于存放操作符
2.通过一个索引值index,来遍历我们需要计算的表达式
3.当我们遍历表达式的时候,如果我们发现当前遍历到的是数字就将其放入数栈中
4.如果我们发现当前遍历到的是符号,就分如下的情况:
(1)如果符号栈为空,就将当前的操作符入符号栈中
(2)如果符号栈有操作符,就进行比较,如果当前操作符的优先级小于或等于栈中操作符,就需要从数栈中pop出两个数,再从符号栈中pop出一个操作符,进行运算,将得到的结果入数栈中,然后将当前操作符入符号栈,如果当前操作符的优先级大于栈中的操作符,就将当前操作符直接入符号栈。
5.当需要计算的表达式遍历完毕,就顺序的从数栈和符号栈中pop出相应的数和符号,并运算
6.最后在数栈中就只有一个数字,就是表达式的值
二、代码实现
public class Calculator {
public static void main(String[] args) {
String expression = "70+2*6-4";
ArrayStack numStack = new ArrayStack2(10);
ArrayStack operStack = new ArrayStack2(10);
int index = 0;
int num1, num2;
int oper = 0;
int res;
char ch = ' ';
String keepNum = "";
while (true) {
ch = expression.substring(index, index + 1).charAt(0);
if (operStack.isOper(ch)) {
if (!operStack.isEmpty()) {
if (operStack.priority(ch) <= operStack.priority(operStack.peek())) {
num1 = numStack.pop();
num2 = numStack.pop();
oper = operStack.pop();
res = numStack.cal(num1, num2, oper);
numStack.push(res);
operStack.push(ch);
} else {
operStack.push(ch);
}
} else {
operStack.push(ch);
}
} else {
keepNum += ch;
if (index == expression.length() - 1) {
numStack.push(Integer.parseInt(keepNum));
} else {
if (operStack.isOper(expression.substring(index + 1, index + 2).charAt(0))) {
numStack.push(Integer.parseInt(keepNum));
keepNum = "";
}
}
}
index++;
if (index >= expression.length()) {
break;
}
}
while (true) {
if (operStack.isEmpty()) {
break;
}
num1 = numStack.pop();
num2 = numStack.pop();
oper = operStack.pop();
res = numStack.cal(num1, num2, oper);
numStack.push(res);
}
int res2 = numStack.pop();
System.out.printf("表达式%s=%d", expression, res2);
}
}
class ArrayStack{
private int maxSize;
private int[] stack;
private int top = -1;
public ArrayStack(int maxSize) {
this.maxSize = maxSize;
stack = new int[maxSize];
}
public int peek() {
return stack[top];
}
public boolean isFull() {
return top == maxSize - 1;
}
public boolean isEmpty() {
return top == -1;
}
public void push(int value) {
if (isFull()) {
System.out.println("栈满");
return;
}
top++;
stack[top] = value;
}
public int pop() {
if (isEmpty()) {
throw new RuntimeException("栈空,没有数据");
}
int value = stack[top];
top--;
return value;
}
public void list() {
if (isEmpty()) {
System.out.println("栈为空,没有数据");
return;
}
for (int i = top; i >= 0; i--) {
System.out.printf("stack[%d]=%d\n", i, stack[i]);
}
}
public int priority(int oper) {
if (oper == '*' || oper == '/') {
return 1;
} else if (oper == '+' || oper == '-') {
return 0;
} else {
return -1;
}
}
public boolean isOper(char var) {
return var == '+' || var == '-' || var == '*' || var == '/';
}
public int cal(int num1, int num2, int oper) {
int res = 0;
switch (oper) {
case '+':
res = num1 + num2;
break;
case '-':
res = num2 - num1;
break;
case '*':
res = num1 * num2;
break;
case '/':
res = num2 / num1;
break;
default:
break;
}
return res;
}
}