码迷,mamicode.com
首页 > 编程语言 > 详细

java实现中缀表达式转后缀表达式

时间:2017-08-13 17:36:33      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:import   append   后缀   bsp   push   exp   tostring   new   length   

技术分享
 1 package postfix;
 2 
 3 import java.util.Stack;
 4 
 5 /**
 6  * 
 7  * @author DELL 将中缀表达式转化为后缀表达式
 8  */
 9 
10 public class Expression {
11     private StringBuffer iExp; // 存储中缀表达式
12     private Stack stack;
13     private StringBuffer pExp; // 存储后缀表达式
14 
15     public Expression(String s) {
16         iExp = new StringBuffer(s);
17         stack = new Stack();
18         pExp = new StringBuffer();
19     }
20 
21     public String toPostfix() throws Exception {
22         while (iExp.length() != 0) {
23             char c = iExp.charAt(0);
24             iExp.deleteCharAt(0);
25             switch (c) {
26             case ‘0‘:
27             case ‘1‘:
28             case ‘2‘:
29             case ‘3‘:
30             case ‘4‘:
31             case ‘5‘:
32             case ‘6‘:
33             case ‘7‘:
34             case ‘8‘:
35             case ‘9‘:
36                 pExp.append(c);
37                 break;
38             case ‘(‘:
39                 stack.push(c);
40                 break;
41             case ‘)‘:
42                 while (stack.peek() != (Object) ‘(‘) {
43                     pExp.append(stack.pop());
44                 }
45                 stack.pop();
46                 break;
47             case ‘+‘:
48             case ‘-‘:
49                 while (!stack.isEmpty() && stack.peek() != (Object) ‘(‘) {
50                     pExp.append(stack.pop());
51                 }
52                 stack.push(c);
53 
54                 break;
55             case ‘*‘:
56             case ‘/‘:
57                 while (!stack.isEmpty() && stack.peek() != (Object) ‘(‘ && stack.peek() != (Object) ‘+‘
58                         && stack.peek() != (Object) ‘-‘) {
59                     pExp.append(stack.pop());
60                 }
61                 stack.push(c);
62                 break;
63             case ‘^‘:
64                 stack.push(‘^‘);
65                 break;
66             default:
67                 System.out.println("出现错误字符"+c);
68                 break;
69             }
70 
71         }
72         while (!stack.isEmpty()) {
73             pExp.append(stack.pop());
74         }
75         return pExp.toString();
76     }
77 
78 }
View Code

撰写时间:2017-08-13 16:50:11

修改时间:

java实现中缀表达式转后缀表达式

标签:import   append   后缀   bsp   push   exp   tostring   new   length   

原文地址:http://www.cnblogs.com/xy-hong/p/7353933.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!