package org.structure.stack;
import java.util.ArrayList;
import java.util.Stack;
/**
* 中缀表达式转化成后缀表达式的过程
* @author cjj_1
* @date 2020-08-07 15:05
*/
public class ToSuffix {
public static void main(String[] args) {
Stack<String> s1= new Stack<String>(); //数栈
Stack<String> s2= new Stack<String>();//操作符栈
String expression = "5 + 6 * ( 9 - 8 + 7 ) - 2";
String[] suffixArr = expression.split(" ");
ArrayList<String> list = new ArrayList<String>();
int num1;
int num2;
String oper;
int res ;
//将数组转换成 list
for(int i =0 ;i< suffixArr.length;i++){
list.add(suffixArr[i]);
}
//开始遍历表达式
for(int i =0;i<list.size();i++){
String item = list.get(i);
if(item.matches("\\d+"))//如果是数字直接入栈是s1
s1.push(item);
else if(!isOper(item)) {//如果是非法字符抛出异常
throw new RuntimeException(item + ":是非法字符");
}else if (item.equals(")")){//如果是右括号,遍历s2中的字符,直到栈顶元素是左括号为止
while (!s2.peek().equals("(")){
oper = s2.pop();
s1.push(oper);
}
s2.pop();//栈顶元素是左括号,出栈
continue;
}else if(s2.empty()|| item.equals("(")||priority(item)>priority(s2.peek())){
s2.push(item);//当s2为空,或者是左括号,或者是栈顶元素的优先级小于当前操作符,入s2
}else if(priority(item)<=priority(s2.peek())){
oper = s2.pop();
s1.push(oper);
while (!s2.isEmpty() && priority(item)<=priority(s2.peek())){
oper = s2.pop();
s1.push(oper);
}
s2.push(item);
}
}
//清空s2中的操作符
while (!s2.isEmpty()){
s1.push(s2.pop());
}
//打印出后缀表达式
s1.forEach(s->{
System.out.print(s+" ");
});
System.out.println(";");
//输出结果为:5,6,9,7,-,*,2,-,+, 是我们的后缀表达式
}
/**
* 运算数据
* @param num1
* @param num2
* @param oper
* @return
*/
public static int calcalator(int num1,int num2,String oper){
int res=0;
switch (oper){
case "*":
res = num2*num1;
break;
case "/":
res = num2/num1;
break;
case "+":
res = num2+num1;
break;
case "-":
res = num2-num1;
break;
default:
res=-1;
break;
}
return res;
}
/*
* 比较操作符的优先级
* @author cjj_1
* @date 2020-08-06 11:50:31
* @param oper
* @return
**/
public static int priority(String oper){
if(oper.equals("*") || oper.equals("/"))
return 1;
else if(oper.equals("+") || oper.equals("-"))
return 0;
else
return -1;
}
//是否是操作符
public static boolean isOper(String oper){
if(oper.equals("+")||oper.equals("-")||oper.equals("*")||oper.equals("/")||oper.equals("(")||oper.equals(")"))
return Boolean.TRUE;
return Boolean.FALSE;
}
//是否是左括号
public static boolean isLeftBracket(String oper){
if(oper.equals("("))
return Boolean.TRUE;
return Boolean.FALSE;
}
//是否是右括号
public static boolean isRightBracket(String oper){
if(oper.equals(")"))
return Boolean.TRUE;
return Boolean.FALSE;
}
}
中缀表达式转化成后缀表达式,优化版本1
最新推荐文章于 2020-10-05 15:26:32 发布