-
Notifications
You must be signed in to change notification settings - Fork 1
/
MidToPosT.java
119 lines (113 loc) · 2.67 KB
/
MidToPosT.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package ljf;
public class MidToPosT {
// 定义符号的优先级
public static int Precedence(char sign) {
switch (sign) {
// +、-都为1
case '+':
case '-':
return 1;
// *、/为2
case '*':
case '/':
return 2;
case '(':
case ')':
default:
return 0;
}
}
/**************** 中缀表达式转换成后缀表达式 ********************/
public static String[] Change(String str) {
String[] s2 = new String[Test.MAX_RANGE];
// #为结束符
String s1 = str + "#";
// 定义大小为20的String类型的栈
Stack<Character> T = new Stack<Character>(Test.MAX_RANGE);
int i = 0, j = 0;
char ch;
String temp = " ";
T.push('@');
ch = s1.charAt(i);
while (ch != '#') {
// 遇到'('就进栈
if (ch == '(') {
T.push(ch);
ch = s1.charAt(++i);
} else if (ch == ')') {
// 遇到')'就把栈中'('后的符号全部出栈
while (T.getTop() != '(')
s2[j++] = String.valueOf(T.pop());
T.pop();
ch = s1.charAt(++i);
} else if (ch == '+' || ch == '-' || ch == '*' || ch == '/') {
char w = T.getTop();
while (Precedence(w) >= Precedence(ch)) {
s2[j++] = String.valueOf(w);
T.pop();
w = T.getTop();
}
T.push(ch);
ch = s1.charAt(++i);
} else {
if ((ch >= '0' && ch <= '9') || ch == '.') {
int k = i;
int flag = 1;
int arr = 0;
int q = 0;// 记录到下一个位置
for (; s1.charAt(i) >= '0' && s1.charAt(i) <= '9'; i++) {
if (i == s1.length() - 1) {
flag = 0;
break;
}
}
if (flag == 1) {
q = i;
i--;
for (int t = k; t <= i; t++) {
int single = Integer.parseInt(String.valueOf(s1
.charAt(t)));
for (int p = t; p < i; p++) {
single = single * 10;
}
arr = arr + single;
}
i = q;
} else {
q = i;
q++;
for (int p = k; p <= i; p++) {
int single = Integer.parseInt(String.valueOf(s1
.charAt(p)));
for (int t = p; t < i; t++) {
single = single * 10;
}
arr = arr + single;
}
i = q;
}
s2[j++] = String.valueOf(arr);
ch = s1.charAt(i);
}
}
}
ch = T.pop();
while (ch != '@') {
s2[j++] = String.valueOf(ch);
ch = T.pop();
}
s2[j++] = "#";
return s2;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] postfix = Change("(25)+3*(6/2)");
String[] infix=PostToMid.getInfixByPostfix(postfix);
for (int i = 0; !postfix[i].equals("#"); i++) {
System.out.println(postfix[i]);
}
for (int i = 0; !infix[i].equals("#"); i++) {
System.out.print(infix[i]);
}
}
}