private static Scanner in;
public static void main(String[] args) {
System.out.println("input");
in = new Scanner(System.in);
char flag;
String s = in.nextLine();
Stack<Character> st = new Stack<Character>();
Stack<Character> rlt = new Stack<Character>();
st.push('#');
for(int i = 0;i<s.length();i++){
flag = s.charAt(i);
switch(flag){
case'(':
st.push(flag);
break;
case')':
while(st.peek() != '('){
rlt.push(st.pop());
}
st.pop();
break;
case'+':
case'-':
while(st.peek()!='#'){
if(st.peek() == '(')
break;
else{
rlt.push(st.pop());
}
}
st.push(flag);
break;
case'*':
case'/':
while(st.peek()!='#' && st.peek()!='+' && st.peek()!='-'){
if(st.peek() == '(')
break;
else
rlt.push(st.pop());
}
st.push(flag);
break;
default :
rlt.push(flag);
}
}
while(st.peek()!='#'){
rlt.push(st.pop());
}
String result ="";
while(!rlt.isEmpty()){
result = result+rlt.pop();
}
StringBuffer sb = new StringBuffer(result);
System.out.println(sb.reverse().toString());
输入表达式 输出逆波兰式
最新推荐文章于 2022-11-27 15:41:18 发布