逆波兰-后缀表达式

中缀表达式转后缀表达式;
规则:
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();  
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值