package calc.PolandNotation;
import calc.MCalc;
import java.util.ArrayList;
import java.util.List;
/**
* 逆波兰表达式
*/
public class PolandCalc {
public static void show(){
String suffixExpression = "( 2 0 0-1 5 4) * (3/1)";
List<String> resultstr = handleExpression(suffixExpression);
List<String> res = middleConvertTail(resultstr);
int result = calculate(res);
System.out.println(result);
}
/**
* 去除表达式中的空格,并将数据与符号分开
* @param str
* @return
*/
public static List<String> handleExpression(String str){
List<String> list = new ArrayList<String>();
String mstr ="";
//去除表达式中的空格
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c == ' '){
continue;
}else {
mstr += c;
}
}
str = mstr;
mstr ="";
for (int i = 0; i < str.length(); i++) {
String temp = String.valueOf(str.charAt(i));
if (temp.matches("\\d+") ){
mstr+=temp;
}else {
if (mstr.length()>0){
list.add(mstr);
mstr = "";
}
list.add(temp);
}
}
return list;
}
/**
* 中缀表达式转后缀表达式
* @param res
* @return
*/
public static List<String> middleConvertTail( List<String> res){
String[] strres1 = new String[100];
String[] strres2 = new String[100];
//创建栈
MCalc<String> calcstack = new MCalc<String>(strres1);
MCalc<String> deststack = new MCalc<String>(strres2);
for (String item : res) {
if (item.matches("\\d+")){
deststack.push(item);
}else {
//判断计算栈是否为空
if (!calcstack.isEmpty()){
//判断符号是否为括号
int pri = calcstack.priority(item.charAt(0));
if (pri>1){
//判断是左括号还是右括号
if (pri == 2){
//左括号直接进栈
calcstack.push(item);
}else if (pri == 3){
//右括号弹出到目标栈至左括号停止
while (!calcstack.isEmpty()){
if(calcstack.getTop().equals("("))
{
//把左括号弹出
calcstack.pop();
break;
}else {
deststack.push(calcstack.pop());
}
}
}
}else {
//不是括号
//当前符号优先级大于栈顶优先级
int toppri = calcstack.priority(calcstack.getTop().charAt(0));
if (toppri<2){
if (calcstack.priority(item.charAt(0))>toppri){
calcstack.push(item);
}else {
//从计算栈弹出元素到目标栈
deststack.push(calcstack.pop());
//在把符号压入计算栈
calcstack.push(item);
}
}else {
calcstack.push(item);
}
}
}else {
//计算栈为空
calcstack.push(item);
}
}
}
//把计算栈剩余内容全部弹出目标栈
while (!calcstack.isEmpty()){
deststack.push(calcstack.pop());
}
List<String> list = new ArrayList<String>();
while (!deststack.isEmpty()){
list.add(0,deststack.pop());
}
return list;
}
public static int calculate(List<String> ls){
String[] res = new String[100];
//创建栈
MCalc<String> stack = new MCalc<String>(res);
for (String item : ls) {
//匹配数字就入栈
if (item.matches("\\d+")) {
stack.push(item);
} else {
//匹配符号就计算
int num2 = Integer.parseInt(stack.pop());
int num1 = Integer.parseInt(stack.pop());
int result = 0;
if (item.equals("+")) {
result = num1 + num2;
} else if (item.equals("-")) {
result = num1 - num2;
} else if (item.equals("*")) {
result = num1 * num2;
} else if (item.equals("/")) {
result = num1 / num2;
} else {
throw new RuntimeException("运算符出错!!!");
}
stack.push("" + result);
}
}
return Integer.parseInt(stack.pop());
}
}
逆波兰表达式计算器---中缀表达式转后缀表达式
最新推荐文章于 2024-07-28 17:51:47 发布