中缀表达式转后缀表达式;
规则:
1.从左到右遍历中缀表达式的每个符号和数字,若是数字就输出,成为后缀表达式的一部分。
2.如果是符号则要判断与栈顶符号的优先级,是右括号或者不高于(等于或小于)栈顶的优先级,则栈顶元素依次输出,当前符号进栈。
3.‘(’>’*’ ‘/’>’+’ -’ 优先级
4.当读取完所有内容后,输出栈中的剩余元素。
import java.util.ArrayList;
import java.util.Stack;
public class StackTest {
private Stack<Character> stack = null;
private String testString = null;
private int flag = 0;
public StackTest(String testString ) {
this.stack = new Stack<Character>();
this.testString = testString;
}
private void analysisString(){
for(int i=0;i<testString.length();i++){
char c = testString.charAt(i);
if(c == '+'|| c== '-'){
if(stack.isEmpty() ||stack.peek() == '('){
stack.push(c);
}else{
while(!stack.empty()&&(stack.peek()=='+'||stack.peek()=='-'||
stack.peek()=='*'||stack.peek()=='/')){
System.out.print(stack.pop()+" ");
}
stack.push(c);
}
}else if(c == '*'||c == '/'){
if(stack.isEmpty() ||stack.peek() == '('){
stack.push(c);
}else{
while(!stack.empty()&&(stack.peek()=='*')||stack.peek()=='/'){
System.out.print(stack.pop()+" ");
}
stack.push(c);
}
}else if(c == '('){
stack.push(c);
}else if(c == ')'){
while(!stack.empty()&&(stack.peek()!='(')){
System.out.print(stack.pop()+" ");
}
stack.pop(); //让(出栈
}else{
if(c == '%' && flag == 0){ //%和flag=0表示开始读入一个连续的数字
flag = 1;
continue;
}
if(c == '%' && flag == 1){
flag = 0;
System.out.print(" "); //%和flag=1表示最后一个连续数字已输出,输出空格
continue;
}
if(flag == 1){
System.out.print(c);
}else{
System.out.print(c+" "); //输出数字或空格
}
}
}
if(!stack.isEmpty()) { //当所有数字读取完毕后让,栈中的所有元素出栈
while (!stack.isEmpty()) {
System.out.print(stack.pop()+" ");
}
}
}
public static void main(String[] args) {
StackTest testStacknew = new StackTest("%17129%+(3-1)*3+%10%/2"); //%代表输入的是一个连续的数字
testStacknew.analysisString();
}
}