/*
骑马订式为后缀式' 12(2231 )4)-5 )==1222314 )5-
首先,将骑马订格式转换为骑马订字符串list,然后单击[12,(,22,31,),*,4,-,5]
在步骤2中,使骑马订字符串list与后缀表达式对应list [12、(、22、31、)、*、4、)、-、5 ]-[ 12、22、31、4、*、5、-]
具体步骤:
初始化两个堆栈,存储s1运算符堆栈、s2中间结果的堆栈
遍历骑马订字符串list
数字情况下,直接进入堆栈s2;
“”时,直接进入堆栈s1;
" ) "时,依次弹出符号堆栈s1的堆栈顶部运算符,将其放入堆栈s2中直到遇到左括号,从堆栈中提取左括号,删除括号对;
在运算符(加减乘除)情况下,与s1堆栈顶部运算符的优先级大小:进行比较
a .如果S1为空或堆栈顶部运算符为“”,则将此运算符直接放入堆栈;
b .否则,即使优先级高于堆栈顶部运算符,也将此运算符放入堆栈;
c .否则,弹出s1堆栈顶部的运算符,堆栈到s2,继续从a循环。
遍历结束后,依次弹出s1的其馀运算符,添加s2。
依次弹出s2中的元素时,结果的反序为与骑马订表达式相对应的后缀表达式。
*/
公共类infixtopostfixdemo {
//步骤1 .将骑马订格式转换为骑马订字符串列表,便于遍历。
//'12 () 2231 ) *4)-5 )=[12,),22,31,),*,4,),-,5]
publiclisttoinfixlist (字符串exp ) {
List res=new ArrayList (;
int i=0;
//保存遍历过程中产生的数字,连续的数字连成一个数字
stringbuilder sb=new stringbuilder (;
while(Iexp.Length () ) ) ) ) )。
if (! Character.isdigit(exp.Charat(I ) ) }
res.add(exp.Charat(I ) '); //如果当前字符不是数字,则直接添加结果
I;
} else {
sb.delete(0,sb.length ) ); //先清除
while(Iexp.length ) ) Character.isdigit ) exp.charat(I ) ) }
sb.append(exp.Charat ) I );
I;
}
res.add(sb.tostring ) );
}
}
返回RES;
}
//在步骤2中将骑马订式字符串列表转换为后缀式字符串列表。
//[12,22,31,*,4,5 ]-[ 12,22,31,4,*,5,-]
publiclisttopostlist (列表列表) {
堆叠S1=新堆叠(; //符号堆栈
//保存中间结果
列表S2=new ArrayList (; //转换过程中,没有pop操作,在后面按相反顺序输出,所以用list代替堆栈
for (字符串项3360列表) {
if(item.Matches('d ' ) ) S2.add ) item; //如果是数字的话就输入s2
elseif(item.equals (' ) ) ) S1.push ) item; //左括号时,进入堆栈s1
对于elseif(item.equals (' ) ) /右括号,依次弹出符号堆栈s1堆栈顶部的运算符,按s2直到到达右括号位置,然后删除右括号对
while (! s1.peek ().equals (' ) ) ) ) )。
S2 .添加(S1.pop ) );
}
s1.pop (; //去掉左括号,继续循环,括号对也就没有了
(else(/此时,遇到的是加减乘除运算符
//当前运算符的优先级=s1的堆栈顶部运算符的优先级通过弹出s1的运算符添加到s2中
while (! S1.empty (优先级) S1.peek ) )=优先级(item ) ) S2.add (S1.pop ) );
S1 .推送(item );
}
}
//S1中依次跳过剩下的运算符,添加到s2中
while (! s1.empty () }
S2 .添加(S1.pop ) );
}
返回S2;
}
私有内优先级(stringop )。
if(''.equals(op )|-'.equals ) )返回1;
if((*.equals(op )|)/(.equals ) )返回2;
返回0; //左括号时返回0
}
//计算后缀表达式字符串列表
publicdoublecalculatepoland{
堆叠=新堆叠(;
for(strings:list ) {
双精度N1,n2;
交换机(s ) {
case '*':
n1=stack.pop (;
n2=stack.pop (;
sack.push(N1*N2 );
布雷克;
case '/':
n1=stack.pop (;
n2=stack.pop (;
sack.push(N2/N1 );
布雷克;
case ' ':
n1=stack.pop (;
n2=stack.pop (;
stack.push(N1N2 );
布雷克;
case '-':
n1=stack.pop (;
n2=stack.pop (;
sack.push(N2-N1 );
布雷克;
默认:
sack.push (双精度. parse双精度(s ) );
布雷克;
}
}
返回堆栈. pop (;
}
publicstaticvoidmain (字符串[ ] args ) {
字符串exp=' 12 () 2231 ) *4)-5 );
infixtopostfixdemoapp=newinfixtopostfixdemo (;
listinfixlist=app.toinfixlist (exp ); //步骤1
列表post list=app.topos tlist (infix list; //步骤2
doubleres=app.calculate Poland (后列表); //步骤3
系统. out.println (infix list );
system.out.println (后列表;
system.out.println(RES;
}
}