最后
由于篇幅限制,小编在此截出几张知识讲解的图解
//栈空
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(“栈空,出栈失败!”);
}
return stack[top–]; //先得到stack[top],然后top–
}
//返回栈顶值
public int peek(){
return stack[top];
}
//遍历(从栈顶向下)
public void show(){
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(char operator){
if (operator == ‘*’ || operator == ‘/’){
return 1;
}else if (operator == ‘+’ || operator == ‘-’){
return 0;
}else return -1; //假设只有加减乘除
}
//判断是不是运算符
public boolean isOperator(char value){
return value == ‘+’ || value == ‘-’ || value == ‘*’ || value == ‘/’;
}
//两数计算方法
public int cal(int num1,int num2,char operator){
int result = 0; //计算结果
switch (operator){
case ‘+’:
result = num2 + num1;
break;
case ‘-’:
result = num2 - num1;
break;
case ‘*’:
result = num2 * num1;
break;
case ‘/’:
result = num2 / num1;
break;
}
return result;
}
}
主要实现计算的逻辑。
public class Calculate {
public static void main(String[] args) {
String expression = “5+40*4-3”; //162
AStack numStack = new AStack(10); //数栈
AStack opeStack = new AStack(5); //运算符栈
//定义需要的变量
int index = 0; //用于扫描表达式
int num1 = 0;
int num2 = 0;
int ope = 0;
int res = 0; //用于临时保存两数运算结果
char ch = ’ '; //每次扫描得到的字符
String keepNum = “”; //用于拼接多位数
//扫描表达式
while (true){
//扫描一个表达式字符
ch = expression.substring(index,index+1).charAt(0);
//判断ch是数还是运算符,并处理
if (opeStack.isOperator(ch)) {
//是运算符
if (opeStack.isEmpty()){
//运算符栈为空,直接入栈
opeStack.push(ch);
}else {
//不为空
if (opeStack.priority(ch) > opeStack.priority((char) opeStack.peek())){
//新的运算符优先级大于栈顶运算符的优先级,直接入栈
opeStack.push(ch);
最后
还有Java核心知识点+全套架构师学习资料和视频+一线大厂面试宝典+面试简历模板可以领取+阿里美团网易腾讯小米爱奇艺快手哔哩哔哩面试题+Spring源码合集+Java架构实战电子书+2021年最新大厂面试题。
.(img-2lz6ZiRm-1715533135049)]