- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNiBoLan.java
More file actions
Latest commit
100 lines (97 loc) · 3.01 KB
/
Copy pathNiBoLan.java
File metadata and controls
100 lines (97 loc) · 3.01 KB
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
packagebasic.QueueAndStack;
importjava.util.Stack;
publicclassNiBoLan {
publicstaticvoidmain(String[] args) {
Stringstr=newNiBoLan().niBoLan("2-(2-1)+3-(2-10)");
System.out.println(newNiBoLan().calNiBoLan(str));
}
//后缀表达值计算值
publicintcalNiBoLan(Stringstr) {
Stack<Integer> numStack=newStack<>();
intnum=0;
for (inti=0;i<str.length();i++) {
charc=str.charAt(i);
if(Character.isDigit(c)) {
num=c-'0';
while (i+1<str.length() && str.charAt(i+1)!=' ') {
num=10*num+(str.charAt(i+1)-'0');
i++;
}
numStack.push(num);
i++;//略过空格
}else {
intb=numStack.pop();
inta=numStack.pop();
inttmp;
switch (c) {
case'*':
tmp=a*b;
break;
case'/':
tmp=a/b;
break;
case'+':
tmp=a+b;
break;
case'-':
tmp=a-b;
break;
default:
tmp=0;
break;
}
numStack.push(tmp);
}
}
returnnumStack.pop();
}
/**
* 中缀表达式转后缀表达式
* @param str
* @return
*/
publicStringniBoLan(Stringstr) {
StringBuildersb=newStringBuilder();
Stack<Character> opStack=newStack<>();
for (inti=0;i<str.length();i++) {
charc=str.charAt(i);
if(c==' ') continue;
if(Character.isDigit(c)) {
sb.append(c);
while (i+1<str.length() && Character.isDigit(str.charAt(i+1))) {
sb.append(str.charAt(i+1));
i++;
}
//数字之间以空格分隔
sb.append(' ');
}else {
chartmp;
if(c=='(') opStack.push(c);
if(c==')') while ((tmp=opStack.pop())!='(') sb.append(tmp);
if(c=='*' || c=='/' || c=='+' || c=='-') {
//扫描到的运算符优先级大于栈顶,直接压栈。
while (!opStack.isEmpty() && getPriority(c)<=getPriority((opStack.peek()))) {
sb.append(opStack.pop());
}
opStack.push(c);
}
}
}
while (!opStack.isEmpty()) {
sb.append(opStack.pop());
}
returnsb.toString();
}
intgetPriority(charop) {
switch (op) {
case'+':
case'-':
return1;
case'*':
case'/':
return2;
default:
return0;
}
}
}