1 package datastructure;
2
3 public class Postfix {
4
5 /**
6 * 转为后缀表达式:
7 * 1、如果是"("直接压入栈。
8 * 2、如果是")",依次从栈弹出运算符加到postfix的末尾,直到遇到"(";
9 * 3、如果是运算符,比较扫描到的运算符,和栈顶的运算符。如果扫描到的运算符优先级
10 * 高于栈顶运算符则,把运算符压入栈。否则的话,就依次把栈中运算符弹出加到postfix的末尾,
11 * 直到遇到优先级低于扫描到的运算符或栈空,并且把扫描到的运算符压入栈中。就这样依次扫描,知道结束为止。
12 * 如果是操作数,直接加到postfix末尾
13 * 如果扫描结束,栈中还有元素,则依次弹出加到postfix的末尾。
14 */
15 public static void main(String[] args) throws Exception {
16 String str="a+(b-c/d)*e";//输出abcd/-e*+则正确
17 System.out.println(convertToPostfix(str));
18
19 }
20
21 public static String convertToPostfix(String str) {
22 LinkStack ls= new LinkStack();
23 String postfix=new String();
24 for(int i=0;i<str.length()&&str!=null;i++){
25 char c=str.charAt(i);
26 if(c=='(') //为开括号
27 ls.push(c);
28 else if(c==')') //为闭括号
29 {
30 char tmp=(Character) ls.pop();
31 while(tmp!='(')
32 {
33 postfix=postfix.concat(String.valueOf(tmp));
34 tmp=(Character) ls.pop();
35 }
36
37 }
38 else if(isOperator(c)) //为运算符
39 {
40 if(!ls.isEmpty()) //判断栈中存不存在元素
41 {
42 char tmp =(Character) ls.pop();
43 while(priority(tmp)>=priority(c)){
44 postfix=postfix.concat(String.valueOf(tmp));
45 tmp=(Character) ls.pop();
46 }
47 if(priority(tmp)<priority(c))
48 {
49 ls.push(tmp);
50 ls.push(c);
51 }
52
53
54 }
55 else //空栈直接push
56 ls.push(c);
57
58
59 }
60 else{ //操作数直接输出到字符串后
61 postfix=postfix.concat(String.valueOf(c));
62 }
63 }
64 while(!ls.isEmpty())
65 postfix=postfix.concat(String.valueOf(ls.pop()));
66 return postfix;
67
68
69 }
70
71 public static int priority(char c) {
72 if(c=='^')
73 return 3;
74 if(c=='*'||c=='/'||c=='%')
75 return 2;
76 if(c=='+'||c=='-')
77 return 1;
78 else
79 return 0;
80 }
81
82 public static boolean isOperator(char c) {
83 if(c=='+'||c=='-'||c=='*'||c=='/'||c=='%'||c=='^')
84 return true;
85 else
86 return false;
87 }
88
89
90 }