【算法与数据结构】中缀表达式转为后缀表达式

(转载请注明出处:http://blog.csdn.net/buptgshengod

1.题目介绍

    中缀表达式是将运算符放在运算数中间的写法,如a+b*c。后缀表达式是将运算符放在运算数后面,如abc*+。

2.代码实现部分

  
import java.util.Stack;  
  
public class Main {  
  
    private String testString = null;  
    private Stack<Character> stack = null;  
  
    
    public Main(String testString) {  
        this.testString = testString;  
        this.stack = new Stack<Character>();  
    }  
  
    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.isEmpty()  
                            && (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.peek() == '-' || stack.peek() == '(') {  
                    stack.push(c);  
                } else {  
                    while (!stack.isEmpty()  
                            && (stack.peek() == '/' || stack.peek() == '*')) {  
                        System.out.print(stack.pop());  
                    }  
                    stack.push(c);  
                }  
            } else if (c == '(') {  
                stack.push(c);  
            } else if (c == ')') {  
                char temp = ' ';  
                while ((temp = stack.pop()) != '(') {  
                    System.out.print(temp);  
                }  
            } else {  
                System.out.print(c);  
            }  
        }  
        if (!stack.isEmpty()) {  
            while (!stack.isEmpty()) {  
                System.out.print(stack.pop());  
            }  
        }  
    }  
  
    public static void main(String[] args) {  
        Main testStacknew = new Main("(a-b)*c+d");  
        testStacknew.analysisString();  
    }  
  
}  

运行结果
【算法与数据结构】中缀表达式转为后缀表达式

     

上一篇:Nginx之支持ZendFramework配置


下一篇:中小企业如何部署企业级Wi-Fi安全方案