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 - 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.push(item);
else if(!isOper(item)) {
throw new RuntimeException(item + ":是非法字符");
}else if (item.equals(")")){
while (true){
if(s2.peek().equals("(")){
s2.pop();
break;
}else {
oper = s2.pop();
// num1 = Integer.valueOf(s1.pop());
// num2 = Integer.valueOf(s1.pop());
// res = calcalator(num1,num2,oper);
s1.push(oper);
}
}
continue;
}else if(s2.empty()|| item.equals("(")||priority(item)>=priority(s2.peek())){
s2.push(item);
}else if(priority(item)<priority(s2.peek())){
oper = s2.pop();
s1.push(oper);
while (priority(item)<priority(s2.peek())){
oper = s2.pop();
s1.push(oper);
}
s2.push(item);
}
}
while (!s2.isEmpty()){
s1.push(s2.pop());
}
s1.forEach(s->{
System.out.print(s+" ");
});
//输出结果为: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;
}
}
中缀表达式转后缀表达式
最新推荐文章于 2024-03-09 22:41:20 发布