中缀表达式转换后缀表达式

通过写这个程序最大的收获是判断一个当涉及访问一个容器时,一定要判断容器是否为空,而且更重要的是需要先判断容器是否为空!!!因为把判断写在后面所以一直RE,调了好久才发现.

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
//
// main.cpp
// 中缀变后缀
//
// Created by maochongxin on 2018/9/18.
// Copyright © 2018 Maochongxin. All rights reserved.
//

#include <iostream>
#include <stack>
#include <string>
#include <algorithm>
using namespace std;

bool isOperator(char s) {
return s == '+' || s == '-' || s == '*' || s == '/' || s == '(' || s == ')';
}



bool Priority(char c1,char c2) {
if (c2 == '(') {
return true;
}
if (c1 == c2) {
return false;
}
if ((c1 == '*' || c1 == '/') && (c2 == '+' || c2 == '-')) {
return true;
}
return false;
}

void MidToAft(string cal) {
stack<char> s;
for (int i = 0; i < cal.length(); i++) {
if (!isOperator(cal[i])) {
cout << cal[i] << " ";
} else {
if (cal[i] == ')') {
while (!s.empty() && s.top() != '(') {
cout << s.top() << " ";
s.pop();
}
s.pop();
} else {
if (s.empty()) {
s.push(cal[i]);
} else {
if (cal[i] == '(') {
s.push(cal[i]);
continue;
}
if (!Priority(cal[i], s.top())) {
while (!s.empty() && !Priority(cal[i], s.top())) {
cout << s.top() << " ";
s.pop();
}
}
s.push(cal[i]);
}
}
}
}
while (!s.empty()) {
cout << s.top() << " ";
s.pop();
}
}

//a+b*c+(d*e+f)*g
//a+b*(c-d)-e/f
int main(int argc, const char * argv[]) {
string s;
cin >> s;
MidToAft(s);
return 0;
}
script>