//工具类
package com.itcast.datastructure.stack.computer;
class ComputerUtils {
public static boolean isOperator(int ch){
if(Character.isDigit(ch)){
return false;
}
if (ch=='+'||ch=='/'||ch=='*'||ch=='-'){
return true;
}
throw new RuntimeException("参数错误");
}
public static int priority(int ch){
if(ch=='/'||ch=='*'){
return 2;
}
if(ch=='+'||ch=='-'){
return 1;
}
throw new RuntimeException("参数错误");
}
public static int figure(int num1,int num2,int operator){
int res = 0;
switch (operator){
case '+':res=num1+num2;break;
case '-':res=num2-num1;break;
case '*':res=num1*num2;break;
case '/':res=num2/num1;break;
}
return res;
}
}
package com.itcast.datastructure.stack.computer;
//计算器类
public class ComputerDemo1 {
public static void main(String[] args) {
StackDemo numberStack = new StackDemo(20);
StackDemo operatorStack = new StackDemo(10);
String expression = "10+2*3+4-8/4";
char ch;
int num1,num2,res;
int operator;
String num="";
for (int i = 0; i < expression.length();i++){
ch=expression.charAt(i);
if(ComputerUtils.isOperator(ch)){
if(operatorStack.isEmpty()){
operatorStack.push(ch);
}else {
if(ComputerUtils.priority(ch)<=ComputerUtils.priority(operatorStack.peek())){
num1=numberStack.pop();
num2=numberStack.pop();
operator=operatorStack.pop();
res=ComputerUtils.figure(num1,num2,operator);
numberStack.push(res);
operatorStack.push(ch);
}else {
operatorStack.push(ch);
}
}
}else {
num+=ch-'0';
if(i==expression.length()-1){
numberStack.push(Integer.parseInt(num));
num="";
continue;
}
if(ComputerUtils.isOperator(expression.charAt(i+1))){
numberStack.push(Integer.parseInt(num));
num="";
}
}
}
while (true){
num1=numberStack.pop();
num2=numberStack.pop();
operator=operatorStack.pop();
res=ComputerUtils.figure(num1,num2,operator);
numberStack.push(res);
if(operatorStack.isEmpty()){
break;
}
}
System.out.printf("表达式%s=%d",expression,numberStack.pop());
}
}
//栈
class StackDemo{
private int[] arr;
private int maxSize;
private int top=-1;
public StackDemo(int maxSize){
this.maxSize=maxSize;
arr=new int[maxSize];
}
public boolean isFull(){
return top==maxSize-1;
}
public boolean isEmpty(){
return top==-1;
}
public void push(int value){
if(isFull()){
System.out.println("栈满");
return;
}
arr[++top]=value;
}
public int pop(){
if(isEmpty()){
throw new RuntimeException("栈空");
}
int value=arr[top--];
return value;
}
public int peek(){
if(isEmpty()){
throw new RuntimeException("栈空");
}
return arr[top];
}
public void showDatas(){
for (int temp=top;temp>=0;temp--){
System.out.println("arr["+temp+"] = "+arr[temp]);
}
}
}
数据结构:栈结构实现数学表达式(中缀)的解析
于 2022-05-01 11:08:55 首次发布