java中使用堆栈类的中缀到后缀
我正在尝试使用堆栈在java中编写中缀到后缀的程序。这是我的密码:
import java.io.*;
import java.util.*;
public class ONP{
public static void main(String args[]) throws java.io.IOException, NumberFormatException ,EmptyStackException{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
StringBuilder out= new StringBuilder();
Stack st=new Stack();
for(int i=0;i<n;i++){
String input=br.readLine();
char in[]=input.toCharArray();
int len=input.length();
for (int j=0;j<len;j++){
if (in[j]>='a' && in[j]<='z'){
out.append(in[j]);
}
else if(in[j]=='('){
st.push(new Character(in[j]));
}
else if(in[j]=='+' || in[j]=='-' || in[j]=='*' || in[j]=='/' || in[j]=='^'){
st.push(new Character(in[j]));
}
else if(in[j]==')'){
int k=j;
while(in[k]!='(' && !st.empty() ){
char ch=st.pop().toString().charAt(0);
if(ch!='('&&ch!=')')
out.append(ch);
k--;
}
}
}
out.append("\n");
}
System.out.print(out);
}
}
输入:
((a+t)*((b+(a+c))^(c+d)))
输出:
at+bac++*cd+^
“*”应该在“+^”之后,但它在“++”之后。我找不到窃听器
# 1 楼答案
你需要实现操作员优先,但你没有。你需要查找Dijkstra调车场算法
# 2 楼答案
这只是一个小错误。 在这段代码中,您在“In”数组中查找“(”,这毫无意义。您只想在堆栈中查找它
换成这个就行了
这应该可以修复错误。但还有很多其他细节需要改进。e、 g.将部分代码放入另一个方法中,并使用泛型和自动装箱。使用字符串而不是字符来允许运算符具有多个字符,并实现运算符优先级,因此不需要太多的括号
看看这个