思路:
1.使用数组模拟栈
2. 创建数据栈和运算符栈,遍历字符串
3. 判断该字符是运算符还是数据,如果是数据则入栈,如果是运算符则判断该运算符的与栈中运算符的优先级;如果栈中运算符优先级大,则数据栈pop两个数据进行运算
然后将结果入数据栈,遍历的运算符入运算符栈;如果是遍历的运算符优先级较大,则将该运算符入栈
package com.company;
/**
* @author:抱着鱼睡觉的喵喵
* @date:2021/2/18
* @description:
*/
public class Calculator {
/**
* 使用栈实现计算器的思路:
* 1.创建数据栈和运算符栈,遍历字符串
* 2.判断该字符是运算符还是数据,如果是数据则入栈,如果是运算符则判断该运算符的与栈中运算符的优先级;如果栈中运算符优先级大,则数据栈pop两个数据进行运算
* 然后将结果入数据栈,遍历的运算符入运算符栈;如果是遍历的运算符优先级较大,则将该运算符入栈
*
* @param args
*/
public static void main(String[] args) {
ArrayStack2 numStack = new ArrayStack2(10);
ArrayStack2 opStack = new ArrayStack2(10);
int index = 0;
int num1 = 0;
int num2 = 0;
int op = 0;
int result = 0;
String s = "30*2-1+50";
char ch = ' ';
String temp = "";
while (true) {
ch = s.substring(index, index + 1).charAt(0);
if (opStack.isOp(ch)) {
if (!opStack.isEmpty()) {
if (opStack.priority(ch) <= opStack.priority(opStack.peek())) {
num1 = numStack.pop();
num2 = numStack.pop();
op = opStack.pop();
result = numStack.cal(num1, num2, op);
numStack.push(result);
opStack.push(ch);
} else {
opStack.push(ch);
}
} else {
opStack.push(ch);
}
} else {
//需要考虑多位数的情况
temp += ch;
if (index == s.length() - 1) {
numStack.push(Integer.parseInt(temp));
}else {
if (opStack.isOp(s.substring(index+1,index+2).charAt(0))) {
numStack.push(Integer.parseInt(temp));
temp = "";
}
}
}
index++;
if (index >= s.length()) {
break;
}
}
while (true) {
if (opStack.isEmpty()) {
break;
}
num1 = numStack.pop();
num2 = numStack.pop();
op = opStack.pop();
result = numStack.cal(num1, num2, op);
numStack.push(result);
}
int res2 = numStack.pop();
System.out.println(res2);
}
}
class ArrayStack2 {
private int maxSize;
private int[] stack;
private int top = -1;
public ArrayStack2(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() {
return stack[top];
}
//入栈
public void push(int value) {
if (isFull()) {
System.out.println("栈已满!");
return;
}
top++;
stack[top] = value;
}
//出栈
public int pop() {
if (isFull()) {
System.out.println("栈空!");
throw new RuntimeException("栈空");
}
int result = stack[top];
top--;
return result;
}
//返回运算符的优先级
public int priority(int op) {
if (op == '*' || op == '/') {
return 1;
} else if (op == '+' || op == '-') {
return 0;
} else {
return -1;
}
}
public boolean isOp(char s) {
return s == '+' || s == '-' || s == '*' || s == '/';
}
/**
* 计算
*
* @param num1 出栈的第一个数据
* @param num2 出栈的第二个数据
* @param op 出栈的运算符
* @return
*/
public int cal(int num1, int num2, int op) {
int result = 0;
switch (op) {
case '+':
result = num2 + num1;
break;
case '-':
result = num2 - num1;
break;
case '*':
result = num2 * num1;
break;
case '/':
result = num2 / num1;
break;
default:
break;
}
return result;
}
}